Android中的一个简单的List应用

来源:互联网 发布:对讲机写频软件大全 编辑:程序博客网 时间:2024/05/14 07:32

 


作者:CrazyPebble
出处:http://crazypebble.cnblogs.com/
欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 

原来我以为在Android下使用List,应该是一件很简单的事情,但是——我错了!之前一直看书,跟着书本的例子程序去学习写List,但是仍然没有掌握到技巧。今天突然看到了一个视频教程,感觉自己有点头绪了。这个视频教程的下载地址是www.mars-droid.com,初学者可以去下载学习一下,还是很不错的,绘声绘色!哈哈~

  好了,步入正题吧。

  在Android程序,使用ListView,相对来说比较复杂,不仅仅需要在活动中添加一个ListView,用于现在整个List列表,你还需要一个布局文件,该布局文件控制这个ListView中的每一项记录(每一行)的显示方式。例如:有一个ListView,它有若干行的记录信息,但是每一行有多个字段;如何对这些字段进行控制,就是这个布局文件需要处理的事情。

1、主活动的布局:

  在主活动窗口中,我们只需要简单的添加一个ListView在活动中就可以了,设置好ListView的属性。

2、ListView中每一项的布局:

  我们通过一个xml布局文件控制每一项的布局。比如,下面的xml文件会在每一项上并列放置两个TextView。

Item.xml
<LinearLayout android:layout_height="fill_parent" android:layout_width="fill_parent" android:paddingBottom="1dip" android:paddingLeft="10dip" android:paddingRight="10dip" android:paddingTop="1dip"> <TextView android:id="@+id/user_name" android:layout_width="180dip" android:layout_height="30dip" android:textSize="10pt" android:singleLine="true" /> <TextView android:id="@+id/user_num" android:layout_width="fill_parent" android:layout_height="fill_parent" android:gravity="right" android:textSize="10pt" /></LinearLayout>

3、ListView的java类

  设置主活动继承自ListActivity类

  通过一个ArrayList存储ListView的显示数据

  创建一个SimpleAdapter的实例,将该实例setListAdapter绑定到当前的ListActivity上。

  设置每一项被单击时,所要执行的操作。

MyActivity.java
public class MyActivity extends ListActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.id.main); ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>(); HashMap<String,String> map1 = new HashMap<String,String>(); HashMap<String,String> map2 = new HashMap<String,String>(); HashMap<String,String> map3 = new HashMap<String,String>(); map1.put("user_name", "Allen"); map1.put("user_num", "123"); map2.put("user_name", "Bobo"); map2.put("user_num", "456"); map3.put("user_name", "David"); map3.put("user_num", "789"); list.add(map1); list.add(map2); list.add(map3); SimpleAdapter listAdapter = new SimpleAdapter( this, // Context list, // 绑定的数据源 R.layout.Item, // Item的布局文件 new String[] {"user_name", "user_num"}, // ListView的列名称 new int[] {R.id.user_name, R.id.user_num}); // Item中每个控件的摆放位置 setListAdapter(listAdapter); } @Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); }}

  这个例子是最基本的ListView的例子程序,要好好理解原理,才能更好的应用。至于对程序代码的解释,就不班门弄斧了,大家有空去www.mars-droid.com里面下载视频来看,里面讲解的更加详细。文件名是《01_13_常用控件(三).mp4》

原创粉丝点击