天天看点

android定时更新listview,如何在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,但在onCreate()方法中添加setContentView()调用,以便我们使用最近声明的布局。请记住,我们特别使用android:id="@android:id/list"来识别ListView。这允许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保存到名为“adapter”的变量中。

下一步是从EditText获取输入。这实际上需要一些思考。您可以将OnKeyListener()添加到您的EditText。但是,此侦听器仅接收一些关键事件。例如,如果用户输入“wyw”,预测文本可能会推荐“眼睛”。在用户选择“wyw”或“eye”之前,您的OnKeyListener将不会收到关键事件。有些人可能更喜欢这种解决方案,但我发现它令人沮丧。我想要每个关键事件,所以我可以选择过滤或不过滤。解决方案是TextWatcher。只需创建并将TextWatcher添加到EditText,并在每次文本更改时将ListAdapter Filter传递给过滤器请求。请记得删除OnDestroy()中的TextWatcher!这是最终的解决方案:

private EditText filterText = null;

ArrayAdapter adapter = null;

@Override

protected 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);

}

};

@Override

protected void onDestroy() {

super.onDestroy();

filterText.removeTextChangedListener(filterTextWatcher);

}