2012-12-01 31 views
-1

我一直在閱讀有關過濾列表視圖的一些主題,但我感到困惑,因爲我只有幾個關於適配器和它的不同種類的知識。我發現了一個解決方案,這幾乎和我的問題類似。這是發表Zoleas過濾LIstview,擴展LIst活動

TextWatcher filterTextWatcher = new TextWatcher() { 

     public void afterTextChanged(Editable s) { 
     } 

     public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
     } 

     public void onTextChanged(CharSequence s, int start, int before, int count) { 
      _myAdapter.getFilter().filter(s); 
     } 
    }; 
    _filterText = (EditText) findViewById(R.id.search_box); 
    _filterText.addTextChangedListener(filterTextWatcher); 

我我如何能在Ontextchanged因爲我的適配器看起來像這樣的方法聲明我的適配器混亂的代碼。

setListAdapter(new ArrayAdapter<String>(this, 
      android.R.layout.simple_list_item_1, result)); 

需要關於如何在這裏實現過濾器的幫助是我的完整代碼在我的列表視圖。

protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.firstaid); 
    filterText = (EditText) findViewById(R.id.acET); 
     DbHelper tblFa = new DbHelper(this); 
    tblFa.open(); 
    ArrayList<String> result = tblFa.getFAData(); 
    result = tblFa.getFAData(); 
    setListAdapter(new ArrayAdapter<String>(this, 
      android.R.layout.simple_list_item_1, result)); 
    ListView lv = getListView(); 
    lv.setTextFilterEnabled(true); 
    tblFa.close(); 
    } 

回答

1

嘗試;

EditText edt = (EditText) this.view.findViewById(R.id.editTxtView); 

     edt.addTextChangedListener(new TextWatcher() { 
     public void beforeTextChanged(CharSequence s, int start, int count, int after) { 
     } 

     @Override 
     public void onTextChanged(CharSequence s, int start, int before, int count) { 
      ListView listView = (ListView) view.findViewById(R.id.yourListviewID); 


       YourAdapterOrWhateverAdapter adapter = (YourAdapterOrWhateverAdapter) listView.getAdapter(); 


       adapter.getFilter().filter(s); 



     @Override 
     public void afterTextChanged(Editable s) { 

     } 
+0

哎呀!每次向EditText添加或刪除一個字母時,不需要使用'findViewById()'兩次。爲什麼使用'setAdapter()'傳遞ListView的當前適配器? (對不起,但leenolasco的代碼比這個建議更快。) – Sam

+0

yeap我再次檢查,你說得對。 findViewById()和setAdapter()是不必要的。 – KEYSAN

1

你只需要創建另一個字段變量,就像filterText

ArrayAdapter<String> _myAdapter; 

而且用它onCreate()這樣的:

_myAdapter = new ArrayAdapter<String>(this, 
     android.R.layout.simple_list_item_1, result); 
setListAdapter(_myAdapter); 
+0

生病請嘗試這一個先生 – leenolasco

+0

謝謝先生它現在的工作!我如何使這個搜索是一個字之間的字母? – leenolasco

+0

「我如何使這個搜索是一個字之間的字母?」我不明白。你能舉個例子嗎? – Sam