1、在布局文件中添加一个listview
<ListView android:id="@+id/listView1" android:entries="@array/ctype" android:layout_width="match_parent" android:layout_height="wrap_content"/>
<resources> <string-array name="ctype"> <item>早饭</item> <item>午饭</item> <item>晚饭</item> <item>夜宵</item> <item>其他</item> </string-array> </resources>
运行
3、也可以通过adapter进行设置listview的内容
ListView listView = (ListView)findViewById(R.id.listView1); String[] ctype = new String[]{"男","女","其他"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,ctype); listView.setAdapter(adapter);运行
4、为ListView添加OnItemClickListener事件监听器
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String result = parent.getItemAtPosition(position).toString(); Toast.makeText(MainActivity.this, result,Toast.LENGTH_SHORT).show(); } });
如果程序的窗口仅仅需要显示一个列表,则可以直接让Activity继承ListActivity来实现,继承了ListActivity的类中无需调用setContentView()方法来显示页面,而是可以直接为其设置适配器,从而显示一个列表
public class MainActivity extends ListActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); String[] ctype = new String[]{"早饭","午饭","晚饭"}; ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_single_choice,ctype); setListAdapter(adapter); } }
@Override protected void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); String result = l.getItemAtPosition(position).toString(); Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show(); }