ListView列表視圖,為列表添加列表項有兩種方法,下面用一個列子分別介紹:
在樣式文件中:
- <?xml version="1.0" encoding="utf-8"?>
- <LinearLayout xmlns:Android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:orientation="vertical" >
-
- <TextView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:text="名單:"
- />
-
- <ListView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:entries="@array/sports"
- android:divider="#00FF00"
- />
-
- <ListView
- android:layout_width="fill_parent"
- android:layout_height="wrap_content"
- android:id="@+id/nameList"
- android:divider="#00FF00"
- />
-
- </LinearLayout>
在上面的布局中定義了兩個ListView,第一個ListView通過android:entries指定了列表的項數組:
- <?xml version="1.0" encoding="utf-8"?>
- <resources>
- <string-array name="sports" >
- <item>足球</item>
- <item>籃球</item>
- <item>乒乓球</item>
- <item>網球</item>
- </string-array>
- </resources>
第二個ListView通過ArrayAdapter適配器使用數組來確定列表項,並監聽點擊事件,每點擊用日志輸出打印:
- package cn.class3g.activity;
-
- import android.app.Activity;
- import android.os.Bundle;
- import android.util.Log;
- import android.view.View;
- import android.widget.AdapterView;
- import android.widget.AdapterView.OnItemClickListener;
- import android.widget.ArrayAdapter;
- import android.widget.ListView;
-
- public class ListViewDemo extends Activity
- implements OnItemClickListener{
-
- ListView nameList = null;
- String[] names = {"張三","李四","王五","宋六","豬八"};
-
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- this.setContentView(R.layout.list_layout);
- findViews();
- }
-
- private void findViews() {
- nameList = (ListView) this.findViewById(R.id.nameList);
- //定義一個適配器,同時將定義列表項的數組添加進去
- ArrayAdapter adapter = new ArrayAdapter(this,
- android.R.layout.simple_list_item_1,names);
- nameList.setAdapter(adapter);
- //為列表添加監聽事件
- nameList.setOnItemClickListener(this);
- }
-
- //覆蓋監聽器接口OnItemClickListener的抽象方法 通過日志打印所點擊的列表項信息
- public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
- Log.i("TAG", names[arg2]
- + " position=" + String.valueOf(arg2)
- +" row_id=" + String.valueOf(arg3) );
- }
-
- }
模擬器與日志顯示和輸出效果: