您的位置:首页 > 移动开发 > Android开发

Android ListView 列表控件的简单使用

2012-05-10 22:08 621 查看
ListView 列表是我们经常会使用的控件, 如果想要自定义里面的显示的话是挺麻烦的, 需要新建XML、Class SimpleAdapter这两个文件, 较为麻烦。 如果我们只是想显示两、三行文字在上面, 却又不想那么麻烦呢? 那我们只要新建一个XML就够了。 
  这里以显示一个ListView项里三个TextView为例。 
  首先我们要创建一个XML文件, 这个XML文件是用来作为单个ListView项布局用的。 
  list_row.xml 

Java代码  



<?xml version="1.0" encoding="UTF-8"?>  

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  

android:layout_width="fill_parent"  

android:layout_height="fill_parent"  

android:background="#ffffff"  

>  

<TextView  

android:id="@+id/textTo"  

android:layout_width="wrap_content"  

android:layout_height="wrap_content"  

android:textSize="16dip"  

android:textColor="#333333"  

/>  

<TextView  

android:id="@+id/textOwn"  

android:layout_width="wrap_content"  

android:layout_height="wrap_content"  

android:layout_below="@id/textTo"  

android:textSize="12dip"  

android:textColor="#999999"  

/>  

<TextView  

android:id="@+id/textState"  

android:layout_width="wrap_content"  

android:layout_height="wrap_content"  

android:layout_alignParentRight="true"  

android:textSize="14dip"  

android:textColor="#999999"  

/>  

</RelativeLayout>  

第一个TextView是标题、第二个是内容、第三个是状态 
接下来我们需要在主XML布局文件里面放置一个ListView控件 

Java代码  



<?xml version="1.0" encoding="utf-8"?>  

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  

android:layout_width="fill_parent"  

android:layout_height="fill_parent"  

android:orientation="vertical"  

android:background="#ffffff"  

>  

<ListView  

android:id="@+id/list"  

android:layout_width="fill_parent"  

android:layout_height="fill_parent"  

android:background="#ffffff"  

></ListView>  

</LinearLayout>  

然后,我们要在主Activity里面声明三个成员变量 
undefined代码 
private List<Map<String, Object>> mList; 
private ListView mListView; 
private SimpleAdapter mListAdapter; 

mList是用来存放要显示的数据 
SimpleAdapter是ListView 数据的一个容器, 用来存放显示在ListView上的数据。 对 SimpleAdapter 的数据操作会直接影响到ListView的显示。 

然后, 我们来给mList添加一些要显示的数据 

Java代码  



mList  = new ArrayList<Map<String,Object>>();  

undefined代码   

Map<String, Object> map = new HashMap<String, Object>();  

map.put("First", "这是标题");  

map.put("Next", "这是内容");  

map.put("State", "状态");  

mList.add(map);  

这样就添加了一条数据, 如果要添加多条就重复再添加。 

接下来我们把数据放入到SimpleAdapter/ListView中 

Java代码  



mListAdapter = null;  

mListAdapter = new SimpleAdapter(this, mList, R.layout.list_row,  

new String[]{"First", "Next", "State"},  

new int[]{R.id.textOwn, R.id.textTo, R.id.textState});  

mListView.setAdapter(mListAdapter);  

new SimpleAdapter的参数: 父指针、ArrayList的数据、 布局文件、 要显示的数据的标签、显示在哪些控件上。  后面两个参数顺序一定要对应。 

最后, ListView载入了SimpleAdapter就可以了。 
当然,我们直接操作mList也会影响到ListView的数据。 在修改了mList的数据后,调用SimpleAdapter的notifyDataSetChanged()方法后就可以了。


java大数据处理(3)-千万级生成excel


java大数据处理(2)-千万级FTP下载


java性能编码规范整理二


java性能编码规范整理一

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息