【问题标题】:Filtering using TextWatcher on a ListView backed by a String ArrayAdapter returns empty results在由 String ArrayAdapter 支持的 ListView 上使用 TextWatcher 进行过滤会返回空结果
【发布时间】:2011-08-09 16:58:08
【问题描述】:

在搜索EditText 中输入任何字符时,以下代码会在列表视图中返回 0 个视图。 以下方法来自活动类

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;
}

}

【问题讨论】:

  • 您是否已调试并单步执行代码以查看 getAdapter 究竟返回了什么?

标签: android listview filter android-arrayadapter textwatcher


【解决方案1】:

终于解决了这个问题。我不得不覆盖Info 对象中的toString() 方法。在我的情况下,过滤基于name 字段,因此通过toString() 返回它。
过滤过程对适配器中的每个对象调用toString()

【讨论】:

【解决方案2】:

Here 它说:

返回的适配器可能与传递给的适配器不同 setAdapter(ListAdapter) 但可能是 WrapperListAdapter

这可能与您的问题有关吗?

【讨论】:

  • 没有。我添加了一个成员来持有适配器,但没有解决问题。
  • 您是否调试并单步执行代码以查看到底发生了什么?
  • 是的。当我按下任何键时,listview 正在从适配器获取所有视图(而不仅仅是过滤的视图).. 但它没有在 listview 中显示它们。这是否意味着过滤器有问题?
猜你喜欢
  • 2012-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-01
  • 1970-01-01
  • 2011-07-10
  • 1970-01-01
  • 2015-03-03
相关资源
最近更新 更多