Android常见UI组件之ListView(一)

使用ListView显示一个长的项列表

1、新建一个名为“BasicView5”的Android项目。

2、改动BasicView5.java文件。改动后的程序例如以下:

package com.example.basicview5;

import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends ListActivity {
	String[] presidents = { "Dwight D. Eisenhower", "John F. Kennedy",
			"Lyndon B. Johnson", "Richard Nixon", "Gerald Ford",
			"Jimmy Carter", "Ronald Reagan", "George H. W. Bush",
			"Bill Clinton", "George W. Bush", "Barack Obama" };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// ---no need to call this---//
		// setContentView(R.layout.activity_main)
		setListAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_expandable_list_item_1, presidents));

	}

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

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

}
3、执行结果:例如以下图。为点击“Richard Nixon”后的样子:


具体解释:

(1)BasicView5类扩展了ListActivity类,ListActivity类扩展了Activity类并通过绑定到一个数据源来显示一个项列表;

(2)无需改动main.xml来包括ListView:ListActivity类本身已经包括了一个ListView。所以在onCreate()方法中,不须要调用setContentView()方法来从main.xml文件里载入用户界面;

(3)在onCreate()方法中,使用setListAdapter()方法来用一个ListView以编程方式填充活动的整个屏幕。

ArrayAdapter对象管理将由ListView显示的字符串数组;

(4)单击ListView中的一个列表项时。会触发onListItemClick()方法。

下一篇来实现对ListView定制通用视图~

posted @ 2019-03-14 19:20  mqxnongmin  阅读(106)  评论(0编辑  收藏  举报