Android中ListView的初步認識(二)

來源:互聯網
上載者:User

在Android中使用一個控制項,一般要有兩樣東西,一是樣式,二是資料。

在第一篇中,我們的ListView使用了Android提供的預設樣式android.R.layout.simple_list_item_1,這個樣式其實就是每個item是一個TextView。資料我們是聲明了一個List並賦值的。最後,我們用了這樣一句代碼實現了把這些綁定到ListView中:

ArrayAdapter adpater = new ArrayAdapter(this, android.R.layout.simple_list_item_1,data);

概述

所以這篇主要的學習內容是在ListView中使用的Adpter。

說起Adapter,我第一個想到的就是適配器模式,雖然設計模式學得不怎麼樣,但是這個詞還是記著的。讓我們看一下在API中對Adapter的說明:

An Adapter object acts as a bridge between an AdapterView and the underlying data for that view. The Adapter provides access to the data items. The Adapter is also responsible for making a View for each item in the data set.(Adapter對象在AdapterView和資料之間扮演者橋樑的角色,Adapter提供了通向資料項目的途徑。Adapter還負責為資料集中的每一個資料項目產生view)



Adapter的子類:


以上兩圖來自(http://www.cnblogs.com/devinzhang/archive/2012/01/20/2328334.html)


Adapter有很多子類,ListActivity中用到的是ListAdpter,ListActivity提供setListAdapter方法來出入使用的Adpter

    public void setListAdapter(ListAdapter adapter) {        synchronized (this) {            ensureList();            mAdapter = adapter;            mList.setAdapter(adapter);        }    }

ListAdpter在API中的描述如下:

Extended Adapter that is the bridge between a ListView and the data that backs the list. Frequently that data comes from a Cursor, but that is not required. The ListView can display any data provided that it is wrapped in a ListAdapter.(ListAdapter繼承了Adapter,作為ListView和資料集之間的橋樑。通常,資料來源於Cursor,但是不是必須的。ListView可以顯示任何被ListAdapter所封裝的資料)

但是ListAdpter是個介面,我們用的時候不會直接用它,而是用到實現這個介面的ArrayAdapter,SimpleAdapter,SimpleCursorAdapter。

接下來,我是介紹這幾種adapter的用法:


ArrayAdapter

ArrayAdapter是安卓提供的一個支援泛型的adapter,這個有點是比較方便,而且有預設定義好的幾種樣式供選擇。

ArrayAdapter提供了幾種構造方法:

Public Constructors
ArrayAdapter(Context context, int resource)Constructor
ArrayAdapter(Context context, int resource, int textViewResourceId)Constructor
ArrayAdapter(Context context, int resource, T[] objects)Constructor
ArrayAdapter(Context context, int resource, int textViewResourceId, T[] objects)Constructor
ArrayAdapter(Context context, int resource, List objects)Constructor
ArrayAdapter(Context context, int resource, int textViewResourceId, List objects)Constructor

Parameters
context The current context.
resource The resource ID for a layout file containing a layout to use when instantiating views.(Item對應的布局檔案的id)
textViewResourceId The id of the TextView within the layout resource to be populated(TextView對應的布局檔案的id)
objects The objects to represent in the ListView.(要顯示的資料集)

安卓為我們提供了幾種查用的Item的布局檔案:比如我在第一篇的例子中用到的android.R.layout.simple_list_item_1,這個布局檔案中只有一個TextView

我們可以看一下它的源碼:

 我們也可以使用其它Android提供的設定檔

需要注意的是,因為我在第一篇的例子中使用的android.R.layout.simple_list_item_1這個樣式,在這個樣式中只有一個TextView,所以我可以用只有三個參數的建構函式

ArrayAdapter adpter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,data);

如果在設定檔中有不止一個view,則需要指定資料放到哪個view中,例如如果使用simple_list_item_single_choice在這個設定檔中有兩個TextView則需要四個參數的建構函式

ArrayAdapter adpter = new ArrayAdapter(this, android.R.layout.simple_list_item_single_choice,android.R.id.text1,data);

這兩個的運行結果如





SimpleAdapter

相對於ArrayAdapter,SimpleAdapter提供了更加靈活的構建ListView的方式。

我們看一下它的建構函式:

Public Constructors
SimpleAdapter(Context context, List> data, int resource, String[] from, int[] to)Constructor

Parameters
context The context where the View associated with this SimpleAdapter is running
data A List of Maps. Each entry in the List corresponds to one row in the list. The Maps contain the data for each row,
and should include all the entries specified in "from"
resource Resource identifier of a view layout that defines the views for this list item. The layout file should include at least those named views defined in "to"
from A list of column names that will be added to the Map associated with each item.
to The views that should display column in the "from" parameter. These should all be TextViews. The first N views in this list are given the values of the first N columns in the from parameter.
其中:第二個參數,是我們要顯示的資料集。List中的每一個Item和ListView中的Item對應。Map中的資料和Item中的列對應。注意Map中的鍵應當與from]參數一致.第三個參數,是定義Item樣式的設定檔。第四個參數,是一個數組,要列舉出我們要顯示的資料在map中的鍵。第五個參數,也是一個數組,要列舉出我們要現實資料的Item中的view的id,to中的順序和from中的順序對應。
下面我看看個小例子:item.xml
               

Activity:
package com.example.listview4;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import android.os.Bundle;import android.widget.SimpleAdapter;import android.app.ListActivity;public class MainActivity extends ListActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);SimpleAdapter adapter = new SimpleAdapter(this, getData(), R.layout.item, new String[] {"image","text"}, new int[] {R.id.image,R.id.text});setListAdapter(adapter);}private List> getData(){List> list = new ArrayList>();Map map = new HashMap();map.put("image", R.drawable.ic_launcher);map.put("text", "測試1");list.add(map);Map map1 = new HashMap();map1.put("image", R.drawable.ic_launcher);map1.put("text", "測試2");list.add(map1);Map map2 = new HashMap();map2.put("image", R.drawable.ic_launcher);map2.put("text", "測試3");list.add(map2);return list;}}

下面是運行結果:



SimpleCursorAdapterSimpleCursorAdapter提供了將資料庫中的資料繫結到ListView中的方法。先看一下構造方法:
Public Constructors
SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to)This constructor was deprecated in API level 11. This option is discouraged, as it results in Cursor queries being performed on the application's UI thread and thus can cause poor responsiveness or even Application Not Responding errors. As an alternative, use LoaderManager with a CursorLoader.
SimpleCursorAdapter(Context context, int layout, Cursor c, String[] from, int[] to, int flags)Standard constructor.
Parameters
context The context where the ListView associated with this SimpleListItemFactory is running
layout resource identifier of a layout file that defines the views for this list item. The layout file should include at least those named views defined in "to"
c The database cursor. Can be null if the cursor is not available yet.
from A list of column names representing the data to bind to the UI. Can be null if the cursor is not available yet.
to The views that should display column in the "from" parameter. These should all be TextViews. The first N views in this list are given the values
of the first N columns in the from parameter. Can be null if the cursor is not available yet.
flags Flags used to determine the behavior of the adapter, as per CursorAdapter(Context, Cursor, int).

參數和前面的大同小異,就不介紹了

下面這段代碼是參考API中提供的例子寫的,但是代碼中擷取連絡人資訊的方式在目前的API中已經不被推薦使用,所以僅供學習參考

package com.example.listview5;import android.app.ListActivity;import android.database.Cursor;import android.os.Bundle;import android.provider.Contacts.People;import android.widget.ListAdapter;import android.widget.SimpleCursorAdapter;@SuppressWarnings("deprecation")public class MainActivity extends ListActivity {    @Override    protected void onCreate(Bundle savedInstanceState){        super.onCreate(savedInstanceState);        // Query for all people contacts using the Contacts.People convenience class.        // Put a managed wrapper around the retrieved cursor so we don't have to worry about        // requerying or closing it as the activity changes state.        Cursor mCursor = this.getContentResolver().query(People.CONTENT_URI, null, null, null, People.TIMES_CONTACTED);        startManagingCursor(mCursor);        // Now create a new list adapter bound to the cursor.        // SimpleListAdapter is designed for binding to a Cursor.        ListAdapter adapter = new SimpleCursorAdapter(                this, // Context.                android.R.layout.two_line_list_item,                  mCursor,                                                              new String[] {People.NAME, People.TIMES_CONTACTED},                          new int[] {android.R.id.text1, android.R.id.text2});          // Bind to our new adapter.        setListAdapter(adapter);    }}


其實可以看到SimpleCursorAdapter的用法和SimpleAdapter的用法還是比較類似的,只不過二者的資料來源,是一個從資料庫中取數,另一個是List。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.