若要以SimpleAdapter建立包含RadioButton或是CheckBox的Custom ListView,可依照以下方法︰
1. 將ListView中將各元件設定為以下屬性
android:focusable="false"
android:focusableInTouchMode="false"
android:clickable="false"
2. 建立一個變數以管理RadioButton或是CheckBox的狀態
3. 建立ListView的OnItemClickListener方法以管理RadioButton或是CheckBox的狀態
Example:
//Create data
private ArrayList<<HashMap<String, Object>> itemList;
依照以下格式設定資料來源
Title: 主標題
Content: 副標題(內容)
Checked: 核取狀態(true / false)
final SimpleAdapter simpleAdapter = new SimpleAdapter(this,itemList,R.layout.customListView,new String[]{"Title","Content","Checked"},new int[]{R.id.TextView1,R.id.TextView2,R.id.RadioButton1});
simpleAdapter.setViewBinder(new SimpleAdapter.ViewBinder() {
@Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
//Hide empty textView
if (data == null) {
view.setVisibility(View.GONE);
return true;
}
view.setVisibility(View.VISIBLE);
return false;
}
});
ListView listview = (ListView) findViewById(R.id.ListView1);
listview .setAdapter(simpleAdapter);
listview .setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
RadioButton radiobutton1 = (RadioButton) findViewById(R.id.RadioButton1);
//Save position
for (HashMap<String, Object> data : itemList)
data.put("Checked", false); //Clear state
itemList.get(position).put("Checked", true); //Set current radio button to checked
simpleAdapter.notifyDataSetChanged();
}
});
最後需要取得資料時,直接判斷ArrayList中HashMap的Checked欄位即可得知被選取的資料