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) );
}
}
模拟器与日志显示和输出效果: