1

I have a dialog in Android, as a layout I use this file:

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

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

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

How can I solve the problem?

4

1 に答える 1

1

You can easily set an id through xml. You use the android:id tag.

Your listview node should look something like this:

<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); should work.

于 2012-12-11T22:22:03.273 に答える