2012年12月18日 星期二

Android開發:simpeAdapter和ListView範例實作

ListView在程式開發上常會使用到元件,

然而,在使用上並無法像在.net平台上開發那樣直接指定一個資料來源給他,

或是直接點編輯樣板就可以改成我們所需要的樣式,

在MVC架構底下一切都要手動自己來,

故我整理一個簡單的範例方便學習記憶,

首先在layout方面,在main.xml放一個ListView,

在List.xml放入RelativeLayout,並拉進來兩個TextView來顯示資料,


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

    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:text="TextView"
        android:textColor="@color/blue" />

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginRight="58dp"
        android:text="TextView" />

</RelativeLayout>

執行檔的部分,先加入這兩個Import
import java.util.*;
import android.widget.*;

在activity onCreate之前宣告兩個字串陣列:


  private String[] EngText = {
           "cat", "flower", "hippo", "monkey", "mushroom", "panda", "rabbit", "raccoon"
   };
private String[] Text = {
           "貓", "花", "河馬", "猴子", "蘑菇", "熊貓", "兔子", "浣熊"
   };


onCreate底下的程式碼如下:


  super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView listView=(ListView)findViewById(R.id.listView1);
//建立存放HashMap資訊的ArrayList物件
List<Map<String, String>> list = new ArrayList<Map<String, String>>();
//用迴圈將資料轉換成HashMap型態存進ArrayList裡
for (int i = 0; i < EngText.length; i++) {
Map<String,String> map = new HashMap<String,String>();
map.put("name",EngText[i]);
  map.put("text", Text[i]);
  list.add(map);
}
//利用SimpleAdapter產生動態資訊,this是固定的,之後(1)list為要放入的資料(2)放入資料後排列的樣式(3)對應的先後順序(4)該layout中TextView的ID名稱
 SimpleAdapter adapter = new SimpleAdapter(this,list,R.layout.list,new String[]{"name","text"},new int[] {R.id.name,R.id.text} );

  //將Adapter中的資料給 listView
 listView.setAdapter(adapter);


執行後的結果如下:




沒有留言:

張貼留言