问题描述
我在我的应用程序中使用AppCompat库(com.android.support:appcompat-v7:22.1.0).我在一个片段中创建了一个ActionBar.当我单击菜单项时,它显示一个警告对话框".这是我的代码:
I'm using AppCompat library (com.android.support:appcompat-v7:22.1.0) in my app. I created an ActionBar in a fragment. When I click in a menu item it shows an Alert Dialog. Here is my code:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_new:
showFilterDialog();
return true;
case R.id.action_send:
new sendInventoryTask().execute();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
还有我的showInventoryDialog方法:
And my showInventoryDialog method:
private void showFilterInventoryDialog() {
AlertDialog.Builder alert = new AlertDialog.Builder(getActivity());
LayoutInflater inflater= getActivity().getLayoutInflater();
View v = inflater.inflate(R.layout.dialog_filter_inventory,null);
alert.setView(v);
alert.setTitle(getResources().getString(R.string.filters));
alert.setPositiveButton(getResources().getString(R.string.filter), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// TODO
}
});
alert.setNegativeButton(getResources().getString(R.string.cancel), null);
alert.show();
}
一切正常,但是当我单击菜单项时,logcat向我显示错误:
Everything works fine, but when I click on menu item, the logcat shows me an error:
如何解决这个问题?
推荐答案
在这种情况下,您需要使用主题上下文,即代替
You are required to use the themed context in this case, i.e. instead of
你必须做
new AlertDialog.Builder(getSupportActionBar().getThemedContext());
此外,您还需要遵循此处提供的父主题和windowActionBar提示-
Besides, you also need to follow the parent theme and windowActionBar tip given here - support.v7.app.AlertDialog throws NullPointerException on dismiss
这篇关于活动的LayoutInflater已经安装了Factory,因此我们无法安装AppCompat的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!