Android常见UI组件之ListView(二)——定制ListView

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

**Android常见UI组件之ListView(二)——定制ListView** 这一篇接上篇,展示ListView中选择多个项及实现筛选功能~ 1、在位于res/values文件夹下的strings.xml文件中添加如下代码: ~~~ BasicView5 Settings Hello world! 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 ~~~ 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;//将列表信息存储在strings.xml文件中,再以编程方式读取 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // ---no need to call this---// // setContentView(R.layout.activity_main); ListView listView = getListView();// 获取ListActivity的列表视图 listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);// 可以选择多个项 listView.setTextFilterEnabled(true);//启用筛选功能,在键盘上输入,ListView自动筛选 // getResources()方法以编程方式检索与应用程序捆绑的资源 presidents = getResources().getStringArray(R.array.presidents_array); setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_checked, 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、运行程序,效果如下: ![](https://docs.gechiui.com/gc-content/uploads/sites/kancloud/2016-08-23_57bc06b4620c7.jpg) 4、在activity_main.xml文件中添加代码如下: ~~~
';