**使用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定制通用視圖~
- 前言
- Android應用程序剖析
- (一)——生命周期
- (二)——使用Intent傳數據之通用方式
- (三)——使用靜態變量傳遞數據
- (四)——通過剪切板傳遞數據
- (五)——通過全局變量傳遞數據
- (六)——從Activity返回數據
- adt-bundle-linux-x86_64-20131030下新建工程提示找不到adb和R.java問題的解決
- Eclipse啟動時提示fail to create the Java Virtual Machine問題的解決
- Android常見UI組件之ListView(一)
- Android常見UI組件之ListView(二)——定制ListView
- (七)——顯示對話框窗口
- (八)——顯示進度對話框
- (九)——更復雜的進度對話框
- (十)——使用意圖鏈接活動
- (十一)——從意圖返回結果
- (十二)——使用意圖傳遞數據的幾種方式
- (十三)——碎片(一)
- (十四)——在運行時添加碎片(附源碼)
- (十五)——碎片的生命周期(附源碼)
- (十六)——碎片之間進行交互(附源碼)
- (十七)——使用意圖調用內置應用程序
- (十八)——使用意圖篩選器和實現瀏覽網頁(附源碼)