Android常见UI组件之ListView(一)

最后更新于:2022-04-01 20:16:39

**使用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(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”后的样子: ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-08-23_57bc06b3db790.jpg) 详解: (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定制通用视图~
';