這是一個應用ListView的小範例, 讓Activity產生一個具有清單效果的條列式資料表.
讓我們在layout中放置一個EditText, 二個Button和一個ListView Widget, 並且預設4筆資料在ListView中, 使用者可自行輸入資料, 新增到ListView中或將ListView中的資料刪除.
為觸發點選列表的事件, 需要實作OnItemClickListener.
不過由於這個範例並沒有建立資料庫, 所以所有的變更在退出AP後就會回到原始狀態了>_<
另外如需要更進階的去增加多筆欄位, 色彩, 文字大小....等, Android API中有提供android.widget.BaseAdaoter物件讓開發者也能透過自行定義的Adapter去設計更豐富的畫面, 甚至還能加入圖檔呢!
ListView_malloc.java
package com.tsots.ListView_malloc; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; public class ListView_malloc extends Activity { Context context = ListView_malloc.this; String tag = "ListView_malloc.this"; String[] countriesStr; TextView myTextView; EditText myEditText; Button myButton_add; Button myButton_remove; ListView listview; ArrayAdapteradapter2; List allData; String newData; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); countriesStr = getResources().getStringArray(R.array.array_listview); allData = new ArrayList (); for (int i = 0; i < countriesStr.length; i++) { allData.add(countriesStr[i]); } adapter2 = new ArrayAdapter (this,android.R.layout.simple_list_item_1, allData); myTextView = (TextView) findViewById(R.id.myTextView); myEditText = (EditText) findViewById(R.id.myEditText); myButton_add = (Button) findViewById(R.id.myButton_add); myButton_remove = (Button) findViewById(R.id.myButton_remove); listview = (ListView) findViewById(R.id.listview1); listview.setAdapter(adapter2); myButton_add.setOnClickListener(new Button.OnClickListener() { public void onClick(View arg0) { newData = myEditText.getText().toString(); for (int i = 0; i < adapter2.getCount(); i++) { if (newData.equals(adapter2.getItem(i))) { return; } } if (!newData.equals("")) { adapter2.add(newData); int position = adapter2.getPosition(newData); listview.setSelection(position); myEditText.setText(""); } } }); //替ListView加入被選重的事件 listview.setOnItemClickListener(new ListView.OnItemClickListener() { public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) { myTextView.setText(allData.get(arg2)); myEditText.setText(allData.get(arg2)); } }); //當按下"移除"button, 先判別user是否有選中一筆資料 myButton_remove.setOnClickListener(new Button.OnClickListener() { public void onClick(View arg0) { if (myEditText.getText().toString() != "") { //從ListView移除 allData.remove(myEditText.getText().toString()); listview.setAdapter(adapter2); myEditText.setText(""); if (adapter2.getCount() == 0) { myTextView.setText(""); } } } }); } }//
沒有留言:
張貼留言