2012年3月26日 星期一

SimpleAdapter in Android

參考:http://developer.android.com/reference/android/widget/SimpleAdapter.html

首先先看SimpleAdapter 的Constructor


public SimpleAdapter (Context context, List<? extends Map<String, ?>> data, int resource, String[] from, int[] to)

Since: API Level 1
Constructor
Parameters
contextThe context where the View associated with this SimpleAdapter is running
dataA 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"
resourceResource 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"
fromA list of column names that will be added to the Map associated with each item.
toThe 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.
可以看到SimpleAdapter 需要五個參數
context   上下文
data       看名字就可以想到是數據源 必須是List of Maps
resource 每個Item的template
from       data要用到的值
to           那些值對應到的id





一個一個解決他們
1.上下文不用說了
2.創建List of Maps

Map<String, String> _Data = new HashMap<String, String>();
_Data.put("Title", "Hello");
_Data.put("Name", "Maca");

Map<String, String> _Data2 = new HashMap<String, String>();
_Data2.put("Title", "你好");
_Data2.put("Name", "馬卡");

List<Map<String, String>> _DataList = new ArrayList<Map<String,String>>() ;

_DataList.add(_Data);
_DataList.add(_Data2);

3.建立layout 看要拖拉點放 還是用打的 以下是範例

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

<TextView
android:id="@+id/tvTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />

<TextView
android:id="@+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

4.from:  宣告一個String[]
String[] _StringArray = new String[]{"Title","Name"};
5.from:  宣告一個int[]

int[] _IdArray = new int[]{R.id.tvTitle,R.id.tvName};
6.最後宣告SimpleAdapter

SimpleAdapter _Adapter = new SimpleAdapter(this, _DataList, R.layout.list_template, _StringArray, _IdArray);


7.別忘了把ListView綁定Adapter

ListView _ListView = (ListView)findViewById(R.id.lvMainPage);
_ListView.setAdapter(_Adapter);


效果

沒有留言:

張貼留言