2011-04-27 138 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); 


} 



}