標籤:android listview
最近做一個black ant的溫控系統項目,裡面有很多清單項目,但是用的時候,感覺封裝的已經挺好的了,自己拿過來改改代碼就行了,所以用過之後也沒什麼感覺。現在趁著閑暇時間整理下簡單的ListView,體會下這個東西到底是怎麼個原理。
首先看下實現效果:
其中,每一條清單項目加的是一個Image跟一個TextView,資料來源綁定在了TextView上面。
首先,添加兩個layout檔案:
列表(item)的布局檔案:
<?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"> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_launcher" /> <TextView android:id="@+id/name" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="lhc" /></LinearLayout>
接著是整個Activity的布局檔案:
<?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="vertical" > <ListView android:id="@+id/lv" android:layout_width="wrap_content" android:layout_height="wrap_content" /></LinearLayout>
接著是Activity的代碼:
public class ListDemo extends Activity{private String[] names;//類比資料源private ArrayList<HashMap<String,String>> listItem;//需求的資料結構private ListView mListView;//列表對象@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.listview_activity);initCtrl();//初始化組件mListView.setOnItemClickListener((OnItemClickListener)new OnItemClickListener(){@Overridepublic void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {Toast.makeText(getBaseContext(), "您選擇了 :"+names[arg2], Toast.LENGTH_LONG).show();}});}/*初始化組件*/private void initCtrl() {mListView=(ListView)findViewById(R.id.lv);//獲得listView對象listItem=loadData();//載入資料SimpleAdapter listItemAdapter=new SimpleAdapter(getBaseContext(),/*指明了SimpleAdapter關聯的View的運行環境,也就是當前的Activity*/listItem,/*由Map組成的List,在List中的每條目對應ListView的一行,每一個Map中包含的就是所有在from參數中指定的key*/R.layout.listview_item,/*定義清單項目的布局檔案的資源ID,該資源檔至少應該包含在to參數中定義的ID*/new String[]{"ItemName"},/*將被添加到Map映射上的Key*/new int[] {R.id.name}/*將綁定資料的視圖的Id跟from參數對應,這些被綁定的視圖元素應該全是TextView*/);//設定適配器mListView.setAdapter(listItemAdapter);}/*類比擷取資料來源過程*/private ArrayList<HashMap<String, String>> loadData() {names=new String[]{"can","pppbc","pbc","lhc","can","小火山"};listItem=new ArrayList<HashMap<String,String>>();//遍曆數組for(int i=0;i<names.length;i++){HashMap<String,String> map=new HashMap<String,String>();String name=names[i];map.put("ItemName", name);//以索引值對的形式儲存listItem.add(map);//將HashMap添加到list中}return listItem;}}
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
Android——ListView實現簡單列表