Home - GeorgeLiao1203/HelloGeorge GitHub Wiki
Welcome to the HelloGeorge wiki!
George Edited
ListView Implementation
ListView
"ListView" is a view group that displays a list of scrollable items. The list items are automatically inserted to the list using an "Adapter" that pulls content from a source such as an array or database query and converts each item result into a view that's placed into the list.
ArrayAdapter 範例
ListView- 定義 ArrayList
ListView listView = (ListView) findViewById(R.id.hello_listview);
ArrayList<String> arrayList = new ArrayList<String>();
arrayList.add("listview1");
arrayList.add("listview2");
arrayList.add("listview3");
arrayList.add("listview4");
arrayList.add("listview5");
arrayList.add("listview6");
ListView- Set Adapter
//利用字串陣列製作 Adapter ,顯示樣式為 android.R.layout.simple_list_item_1。
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
ListviewActivity.this,
android.R.layout.simple_list_item_1, mArrayList);
//將 Adapter 放進元件中,設定資料來源。
mListVeiw.setAdapter(adapter);
利用onItemClickListener方便顯示
mListVeiw.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(ListviewActivity.this, mArrayList.get(position),
Toast.LENGTH_SHORT).show();
}
});
notifyDataSetChanged 更新內容
//設定按鈕,按下後更新 ListView 內容。
Button listviewButton= (Button) findViewById(R.id.listview_btn);
listviewButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// 修改陣列內容
mArrayList.set(0,"Liao");
// 通知資料被變動,更新 ListView 顯示內容。
adapter.notifyDataSetChanged();
}
});