Android之UI学习篇十一:ListView控件学习(一)
ListView这个控件使用的非常普遍,关于它的基本介绍,我们来看一下API中的介绍:
Class Overview
A view that shows items in a vertically scrolling list. The items come from the ListAdapter associated with this view.
ListAdapterimplements Adapterandroid.widget.ListAdapter
Known Indirect Subclassesjava.lang.Objectandroid.content.Contextandroid.content.ContextWrapperandroid.view.ContextThemeWrapperandroid.app.Activityandroid.app.ListActivity
正如名字含义,它是Activity的一个子类。
Class OverviewAn activity that displays a list of items by binding to a data source such as an array or Cursor, and exposes event handlers when the user selects an item.
ListActivity hosts a ListView object that can be bound to different data sources, typically either an array or a Cursor holding query results. Binding, screen layout, and row layout are discussed in the following sections.
ListActivity has a default layout that consists of a single, full-screen list in the center of the screen
我可以直接使用内置的默认, full-screen list,当然很多时候要做一些扩充,我们可以自定义screen layout,使用setContentView() in onCreate()来显示定义的ListView, 不过这里有一要求,To do this, your own view MUST contain a ListView object with the id "@android:id/list" (orlist if it's in code)
这样的原因是什么呢?
原因是我们继承ListActivity这个类,使用getListView()来取得它,系统在执行该方法的时候是按照 id= list 去查找,所以我们必须定义Id为" @android:id/list"。知道了吧!
我们通过一个在String.xml文件里面配置多个国家的名称,然后通过适配器ArrayAdapter来显示这些数据到我们的LIstView控件中,并且提供根据用户输入的匹配符,筛选出匹配的国家名称。
运行结果:

大家可以看到国家的名称已经显示在LIstView控件当中了,当我们输入"be"是自动匹配的结果截图:

其实这个自动匹配功能很简单,只要在代码中调用这句代码:listView.setTextFilterEnabled(true);
工程目录结构:

以下是源代码:
MainActivity.java:
<?xml version="1.0" encoding="utf-8"?><resources> <string name="hello">Hello World, MainActivity!</string> <string name="app_name">HelloListView</string> <string-array name="countries_array"> <item>Bahrain</item> <item>Bangladesh</item> <item>Barbados</item> <item>Belarus</item> <item>Belgium</item> <item>Belize</item> <item>Benin</item> <item>Bermuda</item> <item>Bhutan</item> <item>Bolivia</item> <item>Bosnia and Herzegovina</item> <item>Botswana</item> <item>"Bouvet Island</item> <item>Brazil</item> </string-array></resources>
好了,本篇到此结束,往后会做一个更贴近项目的LIstView实例,再跟大家分享交流,谢谢!!

Known Indirect Subclassesjava.lang.Objectandroid.content.Contextandroid.content.ContextWrapperandroid.view.ContextThemeWrapperandroid.app.Activityandroid.app.ListActivity