android – 资源$NotFoundException:AlertDialog中的资源ID#0x0
作者:互联网
我有一个RecyclerView,在其适配器中,我创建了类似于OnLongClickListener的东西,我调用OnEntryLongClickListener以避免混淆.
我正在使用AlertDialog显示包含不同操作的列表项的对话框.但是,我收到以下错误:
E/AndroidRuntime: android.content.res.Resources$NotFoundException: Resource ID #0x0
at android.content.res.Resources.getValue(Resources.java:2345)
at android.content.res.Resources.loadXmlResourceParser(Resources.java:3910)
at android.content.res.Resources.getLayout(Resources.java:2161)
at android.view.LayoutInflater.inflate(LayoutInflater.java:413)
at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
at android.support.v7.app.AlertController$AlertParams.createListView(AlertController.java:734)
at android.support.v7.app.AlertController$AlertParams.apply(AlertController.java:711)
at android.support.v7.app.AlertDialog$Builder.create(AlertDialog.java:883)
at com.mycompany.myapp.ThisActivity$2.onEntryLongClick(ThisActivity.java:135)
at com.mycompany.myapp.adapter.RVAdapter$RVViewHolder.onLongClick(RVAdapter.java:41)
at android.view.View.performLongClick(View.java:5236)
以下是我使用的相关代码:
adapter.setOnEntryLongClickListener(new RVAdapter.OnEntryLongClickListener() {
@Override
public void onEntryLongClick(View view, int position) {
final MiniEntry thisEntry = entryList.get(position);
AlertDialog.Builder builder = new AlertDialog.Builder(getBaseContext());
builder.setTitle(thisEntry.getEntryName()););
builder.setItems(R.array.quickActions, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Other code here
}
});
AlertDialog alert = builder.create(); // The error log points to this line
alert.show();
}
});
mRecyclerView.setAdapter(adapter);
以及我用于数组的XML:
<string-array name="quickActions">
<item>Add to Favourites</item>
<item>More information</item>
</string-array>
我不确定它是否重要,但我从android.support.v7.app.AlertDialog(来自v7支持库)导入AlertDialog.
我怎么解决这个问题?
解决方法:
将AlertDialog.Builder实例化中的getBaseContext()更改为当前的Activity实例.例如:
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
AlertDialog需要某些资源,其值由附加到其使用的Context的主题和样式提供. getBaseContext()返回的Context没有附加的Context,但Activity有.实际上,每当UI组件需要Context时 – 例如,对话框,视图,适配器等 – 当前的Activity通常是您想要使用的.
标签:android-alertdialog,android 来源: https://codeday.me/bug/20191005/1857167.html