[英]Android Dialog root view
I have a dialog in Android, as a layout I use this file: 我在Android中有一个对话框,使用此文件作为布局:
<?xml version="1.0" encoding="utf-8"?> <ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</ListView>
In the Activity I need to add a Adapter to this ListView, I have this: 在“活动”中,我需要向此ListView添加适配器,我具有以下功能:
@Override
protected Dialog onCreateDialog(int id) {
switch(id){
case ADDPLAYERDIALOG:{
Dialog d = new Dialog(this);
d.setContentView(R.layout.training_dialog);
ListView lv = (ListView) d.getCurrentFocus().getRootView();
ListAdapter adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, createNamesList());
lv.setAdapter(adapter);
return d;
}
}
return super.onCreateDialog(id);
}
I get a NullPointerException here: 我在这里得到一个NullPointerException:
ListView lv = (ListView) d.getCurrentFocus().getRootView();
I don't have the id for this ListView widget, because it is a layout XML-file, and I can't just write lv = d.findViewById(R.id.listview);
我没有此ListView小部件的ID,因为它是布局XML文件,我不能只写
lv = d.findViewById(R.id.listview);
How can I solve the problem? 我该如何解决这个问题?
You can easily set an id through xml. 您可以通过xml轻松设置ID。 You use the
android:id
tag. 您使用
android:id
标签。
Your listview node should look something like this: 您的listview节点应如下所示:
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id = "@+id/listview">
</ListView>
Now your lv = d.findViewById(R.id.listview);
现在,您的
lv = d.findViewById(R.id.listview);
should work. 应该管用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.