Android當中,常會去撈取某些地方的資料並做輸出,像這種動態資料的顯示方法就無法直接用layout來處理,必須透過SimpleAdapter來完成。
Layout的部份必須先使用ListView來存放這些動態的訊息
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/TestListView"
/>
</LinearLayout>
接著需要一個固定格式來裝撈出來的動態資訊,因此再建立一個list.xml
list.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" >
<ImageView
android:paddingTop="12dip"
android:layout_alignParentRight="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ItemImage"
/>
<TextView
android:text="TextView01"
android:layout_height="wrap_content"
android:textSize="20dip"
android:layout_width="fill_parent"
android:id="@+id/ItemTitle"
/>
</RelativeLayout>
最後再從程式端去控制
MainActivity.java
package com.example.aaa;
import java.util.ArrayList;
import java.util.HashMap;
import android.os.Bundle;
import android.app.Activity;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//動態資訊 陣列
int [] img = {R.drawable.ic_launcher,R.drawable.ic_launcher,R.drawable.ic_launcher};
String [] arr = {"Test1","Test2","Test3"};
//main.xml的ListView
ListView list = (ListView) findViewById(R.id.TestListView);
//建立存放HashMap資訊的ArrayList物件
ArrayList<HashMap<String, Object>> listItem = new ArrayList<HashMap<String, Object>>();
//將資料轉換成HashMap型態存進ListView裡
for(int i = 0; i < arr.length; i++){
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("ItemImage", img[i]);//Img
map.put("ItemTitle", arr[i]);//Title
listItem.add(map);
}
//利用SimpleAdapter產生動態資訊
SimpleAdapter listItemAdapter = new SimpleAdapter(this,listItem, //套入動態資訊
R.layout.list,//套用自訂的XML
new String[] {"ItemImage","ItemTitle"}, //動態資訊取出順序
new int[] {R.id.ItemImage,R.id.ItemTitle} //將動態資訊對應到元件ID
);
//執行SimpleAdapter
list.setAdapter(listItemAdapter);
}
}
1 Comment
佛祖球球 » Blog Archive » [Android]OnItemClickListener · 13 8 月, 2012 at 2:53 下午
[…] 但使用SimpleAdapter產生動態資訊後要綁定動態事件,就必須使用OnItemClickListener […]
Comments are closed.