android – 在由String ArrayAdapter支持的ListView上使用TextWatcher进行过滤返回空结果
作者:互联网
在输入搜索EditText中的任何字符时,以下代码在listview中返回0个视图.
以下方法来自activty类
private void setupList() {
final ListView lv = (ListView) findViewById(R.id.contactList);
ArrayAdapter<Info> la = new MyListAdapter(this, mInfoList);
lv.setAdapter(la);
lv.setTextFilterEnabled(true);
EditText edit = (EditText) findViewById(R.id.searchbar);
edit.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
@Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
}
@Override
public void afterTextChanged(Editable text) {
Log.d("search", ""+text);
ArrayAdapter<Info> la = (ArrayAdapter<Info>) lv.getAdapter();
la.getFilter().filter(text);
la.notifyDataSetChanged();
}
});
}
这是我的适配器类
public class MyListAdapter extends ArrayAdapter<Info> {
private Bitmap mDefaultProfilePic = null;
Context mContext = null;
public MyListAdapter(Context ctxt, ArrayList<Info> mFriendsAccounts) {
super(ctxt, R.id.name, mFriendsAccounts);
mContext = ctxt;
mDefaultProfilePic = BitmapFactory.decodeResource(ctxt.getResources(), R.drawable.face);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) mContext.getSystemService(Service.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.layout_list_view, null);
}
Info usr = getItem(position);
((TextView)convertView.findViewById(R.id.name)).setText(usr.Name);
((ImageView)convertView.findViewById(R.id.invite)).setTag(position);
if (mImageBitmaps.get(position) != null) {
((ImageView)convertView.findViewById(R.id.profilePic)).setImageBitmap(mImageBitmaps.get(position));
} else {
((ImageView)convertView.findViewById(R.id.profilePic)).setImageBitmap(mDefaultProfilePic);
}
return convertView;
}
}
解决方法:
最后解决了这个问题.我不得不重写Info对象中的toString()方法.在我的情况下,过滤基于名称字段,因此通过toString()返回.
筛选过程在适配器中的每个对象上调用toString().
标签:android,listview,filter,android-arrayadapter,textwatcher 来源: https://codeday.me/bug/20190903/1795311.html