9

我试图在我的android应用程序中更改选项菜单的背景颜色。我正在使用ActionBarSherlock库。我曾尝试这个代码更改选项菜单java.lang.illegalstateexception:已在此layoutinflater上设置了一个工厂

https://stackoverflow.com/a/8475357/584095

但我结束了一个异常“java.lang.illegalstateexception:一个工厂已经设置在这个layoutinflater”的背景色以线

LayoutInflater.setFactory();

我不知道这段代码有什么问题。任何人都可以帮助我解决这个问题吗?

回答

4

发生这种情况是因为您正在使用兼容性库。它设置自己的工厂来处理平台特定的布局。 在调用super.onCreate()之前,您可以尝试在onCreate()方法中设置自己的工厂。这将禁止兼容性库来覆盖工厂,并且您将无法从xml文件中扩充碎片,但样式应该可以工作。

5

为了保持兼容性库的正常工作并避免“java.lang.illegalstateexception:已在此layoutinflater上设置了一个工厂”,您需要获取已设置的Factory的最终引用并在您的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) { 
    // ... 
} 
+1

不工作。抛出“android.view.InflateException:二进制XML文件行#17:错误膨胀类com.android.internal.view.menu.ActionMenuItemView” – MSIslam

+0

实际上没有更多异常抛出,但我的文本颜色仍然是灰色:( –

2

这个工作对我来说:因为版本

LayoutInflater inflater = LayoutInflater.from(context); 
if (inflater.getFactory() != null) { 
    inflater = inflater.cloneInContext(context); 
} 
inflater.setFactory(factory); 
6

有一直支持库change 22.1.0。

,如果你尝试调用getLayoutInflater().setFactory()

您应该使用新的API

或者简单地使用,你会得到一个IllegalStateException的旧版本

  • com.android.support:appcompat-v7:22.0.0
  • com.android.support:appcompat-v4:22.0.0
+0

cud you pls分享一个工作代码? – AndroidGuy

相关问题