1

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

}

我找到了一些答案,但它们对我没有帮助。
我该如何解决这个问题?谢谢。

4

2 回答 2

5

要保持兼容性库正常工作并避免“java.lang.illegalstateexception:已在此 layoutinflater 上设置工厂”,您需要获取对已设置工厂的最终引用并在您自己的 Factory.onCreateView 中调用其 onCreateView。在此之前,必须使用自省技巧来允许您将工厂再设置一次 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) {
    // ...
}
于 2013-09-04T06:00:56.893 回答
-1

你可以试试

LayoutInfalter inflater = getLayoutInflater.cloneInContext(this);

然后用克隆的布局做你需要的事情

但我不知道您的 onCreateView 是否会以这种方式执行

于 2012-10-12T10:34:49.490 回答