您好,欢迎访问一九零五行业门户网

android开发教程之listview使用方法

首先是布局文件,这里需要两个布局文件,一个是放置列表控件的activity对应的布局文件 main.xml,另一个是listview中每一行信息显示所对应的布局  list_item.xml    这一步需要注意的问题是listview 控件的id要使用android系统内置的 android:id=@android:id/list   [注意形式]
main.xml
<?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" > <listview android:id="@android:id/list" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="20dip"/> </linearlayout>
list_item.xml
<?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="horizontal" > <textview android:id="@+id/user_name" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1"/> <textview android:id="@+id/user_id" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1"/> </linearlayout>
然后就设置mainactivity中的代码了:基本思想就是先将数据添加到arraylist中,然后在设置simpleadapter适配器完成设置,入下:
package com.example.android_newlistview; import java.util.arraylist; import java.util.hashmap; import java.util.map; import android.os.bundle; import android.app.activity; import android.app.listactivity; import android.view.menu; import android.widget.simpleadapter; public class mainactivity extends listactivity { string[] from={"name","id"}; //这里是listview显示内容每一列的列名 int[] to={r.id.user_name,r.id.user_id}; //这里是listview显示每一列对应的list_item中控件的id string[] username={"zhangsan","lisi","wangwu","zhaoliu"}; //这里第一列所要显示的人名 string[] userid={"1001","1002","1003","1004"}; //这里是人名对应的id arraylist<hashmap<string,string>> list=null; hashmap<string,string> map=null; @override protected void oncreate(bundle savedinstancestate) { // todo auto-generated method stub super.oncreate(savedinstancestate); setcontentview(r.layout.main); //为mainactivity设置主布局 //创建arraylist对象; list=new arraylist<hashmap<string,string>>(); //将数据存放进arraylist对象中,数据安排的结构是,listview的一行数据对应一个hashmap对象, //hashmap对象,以列名作为键,以该列的值作为value,将各列信息添加进map中,然后再把每一列对应 //的map对象添加到arraylist中 for(int i=0; i<4; i++){ map=new hashmap<string,string>(); //为避免产生空指针异常,有几列就创建几个map对象 map.put("id", userid[i]); map.put("name", username[i]); list.add(map); } //创建一个simpleadapter对象 simpleadapter adapter=new simpleadapter(this,list,r.layout.list_item,from,to); //调用listactivity的setlistadapter方法,为listview设置适配器 setlistadapter(adapter); } }
另外对点击某一行作出响应的方法是覆写onlistitemclick方法,根据返回的position(从0开始):
@override protected void onlistitemclick(listview l, view v, int position, long id) { // todo auto-generated method stub super.onlistitemclick(l, v, position, id); }
更多android开发教程之listview使用方法。
其它类似信息

推荐信息