2011-04-27 140 views
0

请指导我使用此程序。为什么我们需要使用阵列适配器来显示列表?这个“适配器”是什么,我们可以直接在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); 
    } 
} 

回答

2

从Android API参照,

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

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

看看这个页面的开发指南:http://developer.android.com/guide/topics/ui/binding.html

拉尔斯·沃格尔有一个很好的教程也:http://www.vogella.de/articles/AndroidListView/article.html

2

适配器充当既为要显示的信息的容器中,并允许你改变它是如何由显示压倒适配器的getView()方法。通常,默认情况下,适配器将调用用于创建Adapter的Object的toString()方法,并设置TextView中由android.R.layout.simple_list_item_1提供的布局中引用的文本...但通过使用适配器的getView(),可以为列表提供更复杂的布局显示。

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

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


} 



}