我想更改菜单选项的背景颜色。我得到错误:
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() {
<pre><code> 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;
}
});
</code></pre>
<p>} </p>
我找到了一些答案,但它们对我没有帮助。
如何解决这个问题?谢谢。
最佳答案
为了保持兼容性库正常工作并避免出现“java.lang.illegalstateexception: a factory has already been set on this layoutinflater”,您需要获得对已设置工厂的最终引用,并在您自己的 Factory.onCreateView 中调用其 onCreateView .在此之前,必须使用一个内省(introspection)技巧来允许您再次为 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) {
// ...
}
关于android - 错误 : A factory has already been set on this LayoutInflater (change background color of menu options),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12857007/