我设置列表视图的方式有什么问题?

时间:2014-05-17 18:28:09

标签: java android

这是我的主要活动:

package com.dannytsegai.worldgeography;

import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends ListActivity {

    private ListView listview;
    private String[] mContinents;
    private ArrayAdapter<String> adapter;

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

        listview = (ListView) findViewById(R.id.list);
        mContinents = getResources().getStringArray(R.array.continents_array);
        adapter = new ArrayAdapter<String>(this, R.layout.simple_list_item, mContinents);

        listview.setAdapter(adapter);
    }



}

这是我的主要布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >
    </ListView>

</LinearLayout>

我已经完成了代码,但我无法弄清楚它对我来说有什么问题。有人可以帮助我吗?

3 个答案:

答案 0 :(得分:3)

更改此

  

R.layout.simple_list_item

 android.R.layout.simple_list_item_1

答案 1 :(得分:2)

因为您在布局中扩展ListActivity,所以ListVeiw必须具有标识@android:id/list,否则您将获得以下异常:

java.lang.RuntimeException: Your content must have a ListView whose id attribute is 'android.R.id.list'.

要检索ListView,您无需调用findViewById,但可以直接使用返回ListView的getListView()

答案 2 :(得分:0)

试试这个:

public class MainActivity extends ListActivity {

      public void onCreate(Bundle savedInstanceState) {
           super.onCreate(savedInstanceState);
           String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
            "Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
             "Linux", "OS/2" };
           ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                                      android.R.layout.simple_list_item_1, values);
           setListAdapter(adapter);
      }
}

如有疑问,请查看此页:http://www.vogella.com/tutorials/AndroidListView/article.html#listactivit