android - 错误 : A factory has already been set on this LayoutInflater (change background color of menu options)

标签 android android-layout background

我想更改菜单选项的背景颜色。我得到错误:
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/

相关文章:

java - Android 初学者 : Email and Strings

javascript - 如何延迟加载 div 背景图像

php - 使用 CSS 缩小 php 背景图片

android - using 和有什么不一样?和@作为样式限定符?

Android fragment 谷歌地图 V2 : Error inflating class fragment

android - 在音乐停止播放之前要为通知编写什么代码

java - 添加 fragment 时 Activity 布局不会改变

android - 我们可以删除/清除先前设置的 TAG 到 View 吗?

android - Rx Android 我如何在改造 2 中检查 204 代码

css - 悬停链接以使用 css 更改 *PAGE* 背景颜色