列表视图适配器

时间:2011-04-27 17:05:12

标签: android

请指导我这个程序。为什么我们需要使用数组适配器来显示列表?什么是“适配器”,我们可以直接在ListView中显示内容而不需要适配器吗?比如,我们可以设置setListAdapter(名称)而不是setListAdapter(适配器);?谢谢。
这是代码:

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

public class Episode7 extends ListActivity {


    String[] names = {
        "Elliot","Geoffrey","Samuel","Harvey","Ian","Nina","Jessica",
        "John","Kathleen","Keith","Laura","Lloyd"
    };

    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        // Create an ArrayAdapter that will contain all list items
        ArrayAdapter<String> adapter;

        /* Assign the name array to that adapter and 
           also choose a simple layout for the list items */ 
        adapter = new ArrayAdapter<String>(
                this,
                android.R.layout.simple_list_item_1,
                names);

        // Assign the adapter to this ListActivity
        setListAdapter(adapter);
    }
}

3 个答案:

答案 0 :(得分:2)

适配器既可以作为您要显示的信息的容器,也可以通过覆盖适配器的getView()方法来更改它的显示方式。通常,默认情况下,适配器将调用用于创建适配器的Object的toString()方法,并在android.R.layout.simple_list_item_1提供的布局中引用的TextView中设置文本...但是结束 - 使用适配器的getView(),您可以为列表提供更复杂的布局显示。

要回答最初的问题......您必须使用带有ListView的适配器。

答案 1 :(得分:2)

来自android API参考,

  

Adapter对象充当AdapterView与该视图的基础数据之间的桥梁。适配器提供对数据项的访问。适配器还负责为数据集中的每个项目创建视图。

它基本上是一组接口,用于确定列表如何处理数据。您可以在列表中使用不同的预制适配器类,或者如果要显示自定义数据,则可以创建自己的适配器类。

在开发指南中查看此页面:http://developer.android.com/guide/topics/ui/binding.html

Lars Vogel还有一个很好的教程:http://www.vogella.de/articles/AndroidListView/article.html

答案 2 :(得分:0)

我就是这样做的,它对我有用:

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

public class ListViewDemo extends Activity {

// --------- Create your string array, adapter and ListView
String[] items = {"Cars", "Money","Vacation","Electronics",
        "Shoes","Jewelry", "Buku bucks","Cash","Ham","Swag","Straight      Cash","Homies","Roll Dawgs","Nate Dogg","Wiz Khalifa","Mac Miller","Chitty Bang",
        "Sam Adams","Technine","Kanye West","Rims","Escalade","Spreewells","Chrome Rims","24's",
        "Lebron James","Dwayne Wade","Andre Iguodala","Allen Iverson","Jodi Meeks",
        "Levoy Allen","Mo Williams","Eric Snow","Alien Iverson","Laptop","Phone","Tablet"};

ArrayAdapter<String> adapter;
ListView cashList;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);


    cashList = new ListView(this);
    // create the array adapter<String>(context, layout, array)
    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
    // add the adapter to the list
    cashList.setAdapter(adapter);

    // set the list as the content view
    setContentView(cashList);


}



}
相关问题