使用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" };@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);// ---no need to call this---//// setContentView(R.layout.activity_main)setListAdapter(new ArrayAdapter(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();}@Overridepublic 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”後的樣子:
編程方式填充活動的整個螢幕。ArrayAdapter對象管理將由ListView顯示的字串數組;
(4)單擊ListView中的一個清單項目時,會觸發onListItemClick()方法;
下一篇來實現對ListView定製通用視圖~