Android 程式开发:(十二)列表控件 —— 12.1 ListView的基本使用

这段时间公司工作比较忙,又加上自己要做点小项目,所以很久没更新博客了。

言归正传,今天总结一下Android中的列表控件:ListView和Spinner。


ListView可以垂直并可滑动地地显示一些信息。下面阐述如何使用ListView显示一系列的信息。

1、创建一个工程:BasicViews5。

2、Strings.xml中的代码。

<?xml version="1.0" encoding="utf-8"?> <resources> <string name="hello">Hello World, BasicViews5Activity!</string> <string name="app_name">BasicViews5</string> <string-array name="presidents_array"> <item>Dwight D. Eisenhower</item> <item>John F. Kennedy</item> <item>Lyndon B. Johnson</item> <item>Richard Nixon</item> <item>Gerald Ford</item> <item>Jimmy Carter</item> <item>Ronald Reagan</item> <item>George H. W. Bush</item> <item>Bill Clinton</item> <item>George W. Bush</item> <item>Barack Obama</item> </string-array> </resources>

3、BasicViews5Activity.java中的代码。

package net.learn2develop.BasicViews5; import android.app.ListActivity; import android.os.Bundle; import android.view.View; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; public class BasicViews5Activity extends ListActivity { String[] presidents; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // ---no need to call this--- // setContentView(R.layout.main); presidents = getResources().getStringArray(R.array.presidents_array); setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, presidents)); } public void onListItemClick( ListView parent, View v, int position, long id) { Toast.makeText(this, "You have selected " + presidents[position], Toast.LENGTH_SHORT).show(); } }4、按F11调试。


5、点击每一行的信息,将会有信息弹出。


首先会注意到,BasicViews5Activity这个类是继承的ListActivity的。ListActivity又继承自Activity类,同时,ListView可以显示绑定的数据源的数据。所以,现在没有必要去修改main.xml文件去包含一个ListView,因为ListActivity本身就包含了一个ListView。那么,在onCreate()回调中就没有必要去调用setContentView()了。

在onCreate()回调函数中,我们使用setListAdapter()方法,手动地让一个ListView去充满整个Activity。

ArrayAdapter类管理那些被显示的字符串,在这个例子中,我们让ListView使用simple_list_item_1方式显示数据:

setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, presidents));
最后,重写了onListItemClick()方法,当ListView中的数据被点击的时候,这个方法被触发:

public void onListItemClick( ListView parent, View v, int position, long id) { Toast.makeText(this, "You have selected " + presidents[position], Toast.LENGTH_SHORT).show(); }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值