o19830015
o19830015
2012-12-12 02:55
采纳率: 76.7%
浏览 2.8k

android对话框的根视图

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

请高手指教。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • fandyvon
    寒江独 2012-12-12 03:41
    已采纳
    Dialog d = new Dialog(this);
    ListView lv = (ListView) View.inflate(getBaseContext(),R.layout.training_dialog,null);
    d.setContentView(lv);
    ListAdapter adapter = new ArrayAdapter<String>(this,
                android.R.layout.simple_list_item_1, createNamesList());
    lv.setAdapter(adapter);
    
    点赞 评论
  • cytown
    Billy_崔海斌 2012-12-12 03:14

    getCurrentFocus()会返回null

    getCurrentFocus()会返回null

    点赞 评论
  • franzhong
    franzhong 2012-12-12 03:18
     public class MyListView extends Activity {     
            private ListView listView;
            //private List<String> data = new ArrayList<String>();
            @Override
            public void onCreate(Bundle savedInstanceState){
                super.onCreate(savedInstanceState);
    
               listView = new ListView(this);
                listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1,getData()));
                setContentView(listView);
            }      
    
            private List<String> getData(){             
                List<String> data = new ArrayList<String>();
                data.add("测试数据1");
                data.add("测试数据2");
                data.add("测试数据3");
                data.add("测试数据4");             
                return data;
            }
        }
    

    以上是基础调用方法,可以比较一下

    点赞 评论

相关推荐