2014-02-09 3 views
2

안드로이드에서 목록보기로 검색하려고합니다. 내가 텍스트를 입력 할 때 여기 내 코드안드로이드 검색에서 검색 필터보기

 @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"를 입력하면 결과는 비어 있으며 결과는 예상대로 false입니다. 어떻게 해결할 수 있습니까?

+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() 메서드를 공유 할 수 있습니까? (원하는 경우에만) 우리는 다른 방법이 있다면 추가 목록을 만들지 않아도됩니다. –

관련 문제