天天看点

android listactivity 动态更新,如何动态更新Android上的ListView

首先,您需要创建一个具有EditText和ListView的XML布局。

xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:orientation="vertical" >

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:hint="type to filter"

android:inputType="text"

android:maxLines="1"/>

android:layout_width="fill_parent"

android:layout_height="0dip"

android:layout_weight="1"

/> 

这将正确地布局所有内容,在ListView之上有一个很好的EditText。接下来,像平常一样创建一个ListActivity,但是添加一个setContentView()呼叫onCreate()方法,因此我们使用最近声明的布局。记住我们确认了ListView特别是android:id="@android:id/list"..这允许ListActivity知道哪一个ListView我们希望在我们声明的布局中使用。@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.filterable_listview);

setListAdapter(new ArrayAdapter(this,

android.R.layout.simple_list_item_1,

getStringArrayList());

}

现在运行应用程序应该显示您以前的应用程序。ListView上面有一个漂亮的盒子。为了让这个盒子做点什么,我们需要从它中获取输入,并让输入过滤列表。虽然很多人都试着用手做这件事,最 ListView Adapter课程附带一个Filter对象,可用于自动执行筛选。我们只需要从EditText进入Filter..结果发现这很容易。若要运行快速测试,请将这一行添加到您的onCreate()打电话adapter.getFilter().filter(s);

请注意,您需要保存ListAdapter到一个变量来实现这个工作-我已经保存了我的ArrayAdapter从前面转到一个名为“适配器”的变量。

下一步是从EditText..这实际上需要一些思考。您可以添加一个OnKeyListener()敬你的EditText..但是,此侦听器只接收一些关键事件..例如,如果用户输入“wyw”,预测文本可能会推荐“眼睛”。在用户选择“Wyw”或“眼睛”之前,您的OnKeyListener不会收到关键事件。有些人可能更喜欢这个解决方案,但我发现它令人沮丧。我想要每个关键事件,所以我可以选择过滤还是不过滤。解决方案是TextWatcher..只需创建并添加一个TextWatcher到EditText,并通过ListAdapterFilter每次文本更改时都会发出筛选器请求。请记住移除TextWatcher在……里面OnDestroy()!以下是最后的解决方案:private EditText filterText = null;ArrayAdapter adapter = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.filterable_listview);

filterText = (EditText) findViewById(R.id.search_box);

filterText.addTextChangedListener(filterTextWatcher);

setListAdapter(new ArrayAdapter(this,

android.R.layout.simple_list_item_1,

getStringArrayList());}private TextWatcher filterTextWatcher = new TextWatcher() {

public void afterTextChanged(Editable s) {

}

public void beforeTextChanged(CharSequence s, int start, int count,

int after) {

}

public void onTextChanged(CharSequence s, int start, int before,

int count) {

adapter.getFilter().filter(s);

}};@Overrideprotected void onDestroy() {

super.onDestroy();

filterText.removeTextChangedListener(filterTextWatcher);}