Android——关于ListView控件的使用方法

 

本文将就“ListView控件的使用方法”进行简单说明:

1. 新建一个Empty Android Application  Project:

新建项目成功后,eclipse默认为用户构建了一个基本的HelloWorld应用程序框架,在主界面的Layout中,用户将看到屏幕正中间有一个TextView控件,其中的文字内容为:HelloWorld;

2. 新建的项目是基于Activity的,但是在本文中将讲述ListView控件的使用方法,故而需将Activity替换为ListActivity,操作如下:

  a) 打开项目的Work Path中的src文件夹下的com.xxx.xxx文件夹,其中存储着项目的源程序文件“*.java ”,如“MainActivity.java”,将文件中的字段“extends Activity" 替换为"extends ListActitivy”;

  b) 在MainActivity.java文件头,增加"import android.app.ListActivity;";

  c) 打开项目的Work Path中的res文件夹下的layout文件夹,其中存储着项目的界面文件"*.xml",如"MainActivity.xml“,在此界面文件中增加一下ListView控件,并将该新控件id改为"@android:id/list"

注释(摘自Android开发官网):

ListActivity has a default layout that consists of a single, full-screen list in the center of the screen. However, if you desire, you can customize the screen layout by setting your own view layout with setContentView() in onCreate(). To do this, your own view MUST contain a ListView object with the id "@android:id/list" (or list if it's in code).

3. 至此,项目的基本框架已经建好,用户可编译并运用此项目,可以从虚拟机的仿真环境中看至一个空的界面,这是因为用户尚未向ListView中增加Item。如果程序在运行过程中,出现崩溃的情况,说明操作有误,用户可以按第2步操作中的说明,对项目进行修改、完善。

 

4. 下一步,按用户需求,向ListView中增加新的Item:

a) 打开scr目录中com.***.***文件夹下的MainActivity.java源文件,在OnCreate函数的最下方或其它适当的位置,增加以下代码:

//Simulation Database.
String[] str = {"aaa","bbb","ccc","ddd","eee","fff"};
setListAdapter(new ArrayAdapter<String>(this,
		android.R.layout.simple_list_item_1, str));
//android.R.layout.simple_list_item_1 -> @android:id/list
/*
 *Official Reference:
 * 
 * ListActivity has a default layout that consists of a single, 
 * full-screen list in the center of the screen. 
 * However, if you desire, you can customize the screen layout 
 * by setting your own view layout with setContentView() in onCreate(). 
 * To do this, your own view MUST contain a ListView object 
 * with the id "@android:id/list" (or list if it's in code)
 */
getListView().setTextFilterEnabled(true);		

b) 在MainActivity.java源文件的头部,增加以下代码:

import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;


c) 编译项目,在仿真界面的ListView控件中,将出现"aaa","bbb","ccc"等共7条的Item。至此,关于ListView控件的建立工作算是成功了。

(End)

posted @ 2013-03-24 15:15  TechStone  阅读(443)  评论(0编辑  收藏  举报