我有一个带有扩展 ArrayAdapter 的自定义适配器的 ListView。它是 Artist 类型的 ArrayAdapter。
Artist 是一个非常小的类,它有一个名字和一个 ID。Artist 类已覆盖 toString() 以仅返回名称。
我有一个 EditText。EditText 有一个 TextChangeListener 我在我的适配器上调用 .getFilter().filter(chars, callback) 。
在 Filter.Filterlistener().onComplete() 回调中,我打印了计数,它看起来非常好。当我键入时,计数会减少。所以它接缝一切都像宣传的那样工作,但列表保持不变。我试图调用 artistAdapter.notifyDataSetChanged() 来强制列表重绘,但没有任何反应。[见 2.)]
我现在正在修补几天!我很绝望..希望有人可以看看我的代码并告诉我我做错了什么!
谢谢!
这是我所做的:
1.) 像这样定义一个 ListView 和一个 EditText :
<EditText xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_search_text"
android:layout_width="fill_parent"
android:layout_height="35dip"
android:layout_below="@id/header">
</EditText>
<ListView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/list_search"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
2.) 在活动 onCreate() 中设置我的 ListView:
private ListView listView = null;
private ArtistAdapter artistAdapter = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_artists);
artistAdapter = new ArtistAdapter(this, R.layout.row, list); // 'list' is an ArrayList<Artist>
listView = (ListView) findViewById(R.id.list_search);
listView.setAdapter(artistAdapter);
listView.setFastScrollEnabled(true);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int position, long id) {
// do something
}
});
EditText txtSearch = (EditText) findViewById(R.id.list_search_text);
txtSearch.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable arg0) { }
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }
public void onTextChanged(CharSequence chars, int start, int before, int count) {
artistAdapter.getFilter().filter(chars, new Filter.FilterListener() {
public void onFilterComplete(int count) {
Log.d(Config.LOG_TAG, "filter complete! count: " + count);
artistAdapter.notifyDataSetChanged();
}
});
}
});
}
3.) 简而言之,这是我的 ArtistAdapter。我添加了一个 remove() 和 add() 方法:
public class ArtistAdapter extends ArrayAdapter<Artist> implements SectionIndexer {
private List<Artist> items;
/* other stuff like overridden getView, getPositionForSection, getSectionForPosition and so on */
@Override
public void remove(Artist object) {
super.remove(object);
items.remove(object);
}
@Override
public void add(Artist object) {
super.add(object);
items.add(object);
}
}
4.) 我的艺术家也覆盖了 toString():
public class Artist implements Comparable<Artist> {
public String uid;
public String name;
public Artist(String id, String name) {
this.uid = id;
this.name = name;
}
public int compareTo(Artist another) {
return this.name.compareToIgnoreCase(another.name);
}
@Override
public String toString() {
return this.name;
}
}