【Android 开发教程】ListView的基本使用

来源:互联网 发布:拳击手套 知乎 编辑:程序博客网 时间:2024/05/16 08:26

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

言归正传,今天总结一下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();    }