use*_*782 1 android background android-layout
我想更改菜单选项的背景颜色.我得到错误:
FATAL EXCEPTION: main
java.lang.IllegalStateException: A factory has already been set on this LayoutInflater
at android.view.LayoutInflater.setFactory(LayoutInflater.java:277)
我用这个代码:
private void setMenuBackground() {
getLayoutInflater().setFactory(new Factory() {
@Override
public View onCreateView (String name, Context context, AttributeSet attrs) {
if (name.equalsIgnoreCase("com.android.internal.view.menu.IconMenuItemView")) {
try {
LayoutInflater f = getLayoutInflater();
final View view = f.createView(name, null, attrs);
new Handler().post( new Runnable() {
public void run () {
view.setBackgroundColor(Color.GRAY);
}
});
return view;
}
catch (InflateException e) {
}
catch (ClassNotFoundException e) {
}
}
return null;
}
});
Run Code Online (Sandbox Code Playgroud)
}
FATAL EXCEPTION: main
java.lang.IllegalStateException: A factory has already been set on this LayoutInflater
at android.view.LayoutInflater.setFactory(LayoutInflater.java:277) 我找到了一些答案,但他们没有帮助我.
我该如何解决这个问题?谢谢.
为了保持兼容性库的工作并避免"java.lang.illegalstateexception:已经在此layoutinflater上设置了工厂",您需要获得对已设置的Factory的最终引用,并在您自己的Factory.onCreateView中调用其onCreateView.在此之前必须使用内省技巧,以允许您再次将Factory设置为LayoutInflater:
LayoutInflater layoutInflater = getLayoutInflater();
final Factory existingFactory = layoutInflater.getFactory();
// use introspection to allow a new Factory to be set
try {
Field field = LayoutInflater.class.getDeclaredField("mFactorySet");
field.setAccessible(true);
field.setBoolean(layoutInflater, false);
getLayoutInflater().setFactory(new Factory() {
@Override
public View onCreateView(String name, final Context context, AttributeSet attrs) {
View view = null;
// if a factory was already set, we use the returned view
if (existingFactory != null) {
view = existingFactory.onCreateView(name, context, attrs);
}
// do whatever you want with the null or non-null view
// such as expanding 'IconMenuItemView' and changing its style
// or anything else...
// and return the view
return view;
}
});
} catch (NoSuchFieldException e) {
// ...
} catch (IllegalArgumentException e) {
// ...
} catch (IllegalAccessException e) {
// ...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3677 次 |
| 最近记录: |