2

我正在尝试在 android 的列表视图中搜索。这是我的代码

        @Override
    public Filter getFilter(){
       return new Filter(){

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                FilterResults result = new FilterResults();

                if (constraint != null && constraint.toString().length() > 0) {
                    constraint = constraint.toString();
                    List<FoodCell> founded = new ArrayList<FoodCell>();
                    for(FoodCell item: allItemFood){
                         if(item.cellText.toString().contains(constraint)){
                              founded.add(item);
                          }
                     }
                     result.values = founded;
                     result.count = founded.size();
                  }else 
                     result.count = 0;

                return result;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {             
            clear();
            if(results.count != 0){
                 for (FoodCell item : (List<FoodCell>) results.values) {
                       add(item);
                  }
             }                     
             notifyDataSetChanged();
        }

        };
        }



    @Override
public boolean onQueryTextChange(String newText) {
    //check if user deleted a character
    if(length > newText.length()){
        allItemFood = allItemFoodTmp;

    }
    if (TextUtils.isEmpty(newText)) {
        adapter = new CustomListViewAdapter(this, R.layout.listfood,allItemFood);
        getListView().setAdapter(adapter);
        getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    } else {
        adapter.getFilter().filter(newText);
    }
    length = newText.length();
    return true;
}



@Override
public boolean onQueryTextSubmit(String query) {
    return false;
}

假设我们在列表中有以下项目,aa,ab,ac 当我输入文本“aaz”作为搜索查询时,它显示空列表,这是真的,但是当我从搜索查询中删除字符“z”时,结果仍然是空的结果是假的。我该如何解决?

4

1 回答 1

1

不确定您使用哪个小部件来获取搜索文本输入,如果它是 EditView(考虑到我正在回答),那么您应该尝试向其中添加 TextWatcher,然后在 onTextChanged() 方法中插入您的搜索登录名,该登录名将执行每次在 EditText 中添加或删除一个字符时。

如果您正在使用其他东西,请告诉我,我会尽力提供帮助。快乐编码。:)

于 2014-02-10T16:10:48.467 回答