sam*_*jay 9 android background-color options-menu android-optionsmenu oncreateoptionsmenu
我试图在我的Android应用程序中更改选项菜单的背景颜色.我正在使用ActionBarSherlock库.我试过这段代码来改变选项菜单的背景颜色
但我最终得到一个例外"java.lang.illegalstateexception:已经在此layoutinflater上设置了一个工厂"
LayoutInflater.setFactory();
我不知道这段代码有什么问题.任何人都可以帮我解决这个问题吗?
自版本22.1.0起,支持库发生了变化.
如果您尝试呼叫,您将收到IllegalStateException getLayoutInflater().setFactory()
你应该使用新的API
ActionBarActivity或者只是使用旧版本
com.android.support:appcompat-v7:22.0.0com.android.support:appcompat-v4:22.0.0发生这种情况是因为您正在使用兼容性库。它设置自己的工厂来处理平台特定的布局。在调用 super.onCreate() 之前,您可以尝试在 onCreate() 方法中设置自己的工厂。这将不允许兼容性库覆盖工厂,并且您将无法从 xml 文件中扩充片段,但样式应该可以工作。
为了保持兼容性库的工作并避免"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)
| 归档时间: |
|
| 查看次数: |
7461 次 |
| 最近记录: |