2014-02-09 105 views
2

我想在android中的列表视图中搜索。这里是我的代码在android中的过滤器搜索listView

 @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”来自搜索查询,结果保持为空,这是预期的结果。 我该如何解决它?

+0

发布整个适配器 – Blackbelt

+0

没用,包含点击操作代码 –

回答

1

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

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

+1

继承人也是一个例子。 http://www.androidhive.info/2012/09/android-adding-search-functionality-to-listview/ –

+0

我正在使用编辑文本和onTextChanged方法搜索,但我的问题是删除搜索查询,列表中的任何字符在它之后是空的。我通过使用临时列表来存储它的值并在onTextChanged方法中重新分配来解决它 –

+0

好听。 :)你可以分享onTextChanged()方法(只有当你想要的时候),我们可以试着找出是否有其他方法,你可以避免创建额外的列表。 –