【问题标题】:Android Dialog root viewAndroid 对话框根视图
【发布时间】:2012-12-11 22:11:23
【问题描述】:

我在 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>

在Activity中我需要给这个ListView添加一个Adapter,我有这个:

@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);
}

我在这里得到一个 NullPointerException:

 ListView lv = (ListView) d.getCurrentFocus().getRootView();

我没有这个 ListView 小部件的 id,因为它是一个布局 XML 文件,我不能只写 lv = d.findViewById(R.id.listview);

我该如何解决这个问题?

【问题讨论】:

  • 你真的试过给它一个id吗?我不明白为什么它不应该工作。

标签: android layout dialog


【解决方案1】:

您可以通过xml轻松设置id。您使用android:id 标签。

您的列表视图节点应如下所示:

<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>

现在你的lv = d.findViewById(R.id.listview); 应该可以工作了。

【讨论】:

  • 我不同意你的第一点。 ListView 是独生子女,将它包装在布局中会有什么好处?
  • 如果您不指定一个布局,Android 是否会默认使用布局?我记得读过一些关于那个的东西。
  • (我编辑了我的评论以使其更具建设性。)这样想:每当布局只有一个孩子时,Lint 工具就会警告您...查看simple_list_item_1.xml 它只是一个文本视图。
  • 我现在明白你的意思了,是的,除了更漂亮的语法突出显示之外没有任何好处。似乎我遇到了一些小的冗余问题:)
猜你喜欢
  • 2021-08-01
  • 2012-07-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-04
  • 2011-07-11
  • 2013-09-23
  • 1970-01-01
相关资源
最近更新 更多