Android ListView 列表控件的简单使用

  ListView 列表是我们经常会使用的控件, 如果想要自定义里面的显示的话是挺麻烦的, 需要新建XML、Class SimpleAdapter这两个文件, 较为麻烦。 如果我们只是想显示两、三行文字在上面, 却又不想那么麻烦呢? 那我们只要新建一个XML就够了。

  这里以显示一个ListView项里三个TextView为例。

  首先我们要创建一个XML文件, 这个XML文件是用来作为单个ListView项布局用的。

  list_row.xml

<?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控件

<?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里面声明三个成员变量

	private List<Map<String, Object>> mList;	
	private ListView mListView;
	private SimpleAdapter mListAdapter; 


mList是用来存放要显示的数据

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

 

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

 

	mList  = new ArrayList<Map<String,Object>>();
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("First", "这是标题");
	map.put("Next",  "这是内容");
	map.put("State", "状态");
	
	mList.add(map);


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

 

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

 

	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()方法后就可以了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值