简体   繁体   中英

Run-time error while creating a ListView

I am facing this error while creating a ListView.


<ListView
    android:id="@+id/list_view"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />


MainActivity.java

public class MainActivity extends ListActivity {

    ListView l;
    String[] names = {"aaa","bbb","ccc"};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        l = (ListView)findViewById(R.id.list_view);
        ArrayAdapter ad = new ArrayAdapter(this,android.R.layout.activity_list_item,names);
        l.setAdapter(ad);

    }
}

just comment out this section of your code:

setContentView(R.layout.activity_main);

and then replace :

l = (ListView)findViewById(R.id.list_view);
ArrayAdapter ad = new ArrayAdapter(this,android.R.layout.activity_list_item,names);
l.setAdapter(ad);

with:

​setListAdapter(new ArrayAdapter<String>(this,​​​​​​​​​​​​android.R.layout.simple_list_item_1, names));

or you can keep your code and just change ListActivity to Activity

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM