首先是布局文件,这里需要两个布局文件,一个是放置列表控件的activity对应的布局文件 main.xml,另一个是listview中每一行信息显示所对应的布局 list_item.xml 这一步需要注意的问题是listview 控件的id要使用android系统内置的 android:id=”@android:id/list” [注意形式]
上述就是android开发分享android开发教程之listview使用方法的全部内容,如果对大家有所用处且需要了解更多关于Android学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
main.xml
<linearlayout xmlns:android=”https://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
<linearlayout xmlns:android=”https://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适配器完成设置,入下:
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开始):
protected void onlistitemclick(listview l, view v, int position, long id) {
// todo auto-generated method stub
super.onlistitemclick(l, v, position, id);
}
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/addevelopment/940061.html