Android ListActivity應用技巧全解
今天為大家帶來的是有關Android ListActivity的相關內容的介紹。我們可以從這篇文章中介紹的內容詳細的對這一方面的知識進行一個全面的認識。首先看看android.app包里的幾個類。首先是這個在平臺自的例子中被廣泛使用的Android ListActivity。這個類其實就是一個含有一個ListView組件的Activity類。也就是說,如果我們直接在一個普通的Activity中自己加一個ListView也是完全可以取代這個Android ListActivity的,只是它更方便而已,方便到什么程度呢?來做個例子瞧瞧。
- public class HelloTwoB extends ListActivity
- ...{
- public void onCreate(Bundle icicle) ...{
- super.onCreate(icicle);
- setTheme(android.R.style.Theme_Dark);
- setContentView(R.layout.mainb);
- List< String> items = fillArray();
- ArrayAdapter< String> adapter = new ArrayAdapter< String>
(this,R.layout.list_row,items);- this.setListAdapter(adapter);
- }
- private List< String> fillArray()
- ...{
- List< String> items = new ArrayList< String>();
- items.add("日曜日");
- items.add("月曜日");
- items.add("火曜日");
- items.add("水曜日");
- items.add("木曜日");
- items.add("金曜日");
- items.add("土曜日");
- return items;
- }
- @Override
- protected void onListItemClick(ListView l,
View v, int position, long id)- ...{
- TextView txt = (TextView)this.findViewById(R.id.text);
- txt.setText("あすは "+l.getSelectedItem().toString()+"です。");
- }
- }
的確可以簡單到只需準備一個List對象并借助Adapter就可以構造出一個列表。重載onListItemClick方法可以響應選擇事件,利用***個參數可以訪問到這個ListView實例以得到選中的條目信息。這里有一點要說明的,就是如果更簡單的話,其實連那個setContentView都可以不要了,Android也會自動幫我們構造出一個全屏的列表。但是本例中我們需要一個TextView來顯示選中的條目,所以我們需要一個layout.mainb描述一下這個列表窗口。
- < ?xml version="1.0" encoding="utf-8"?>
- < LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/android"- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- < TextView id="@+id/text"
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text=""
- />
- < ListView id="@id/android:list"
- android:layout_width="fill_parent"
- android:layout_height="0dip"
- android:layout_weight="1"
- android:drawSelectorOnTop="false"
- />
- < /LinearLayout>
在Android ListActivity操作中需要注意的是那個ListView的ID,是系統自定義的android:list,不是我們隨便取的,否則系統會說找不到它想要的listview了。然后,在這個listview之外,我們又增加了一個TextView,用來顯示選中的條目。
再來說說這里用到的ArrayAdapter,它的構造函數中第二個參數是一個資源ID,ArrayAdapter的API文檔中說是要求用一個包含 TextView的layout文件,平臺用它來顯示每個選擇條目的樣式,這里的取值是R.layout.list_row,所以,我們還有一個list_row.xml文件來描述這個布局,相當簡單。
- < ?xml version="1.0" encoding="utf-8"?>
- < LinearLayout xmlns:android=
"http://schemas.android.com/apk/res/android"- android:orientation="vertical"
- android:layout_width="fill_parent"
- android:layout_height="fill_parent"
- >
- < TextView id="@+id/item"
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
- < TextView id="@+id/item2"
- xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"/>
- < /LinearLayout>
從ArrayAdapter上溯到BaseAdapter,發現還有幾個同源的Adapter也應該可以使用,象SimpleAdapter和CursorAdapter,還是做個例子來實驗一下吧。
Android ListActivity的相關內容就為大家介紹到這里。
【編輯推薦】