學習筆記-Android之ListView隨EditText輸入內容動態改變

在學習過程之中常常用到各類詞典發現再輸入過程當中有相似AutocompleteTextView的隨着在EditText輸入內容ListView動態變化的效果  本身試着簡單實現如下

實現這種效果主要用到的一個類TextWatcher  以及一個EditText的監聽器addTextChangedListener

實現代碼:

public class DynSearchList_MainActivity extends Activity {

 private ListView listView;
 private MydbHelper dbHelper;
 SQLiteDatabase databases;
 private Cursor c;
 private EditText editText;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dyn_search_list__main);
        
        init();
        //建立數據庫
        dbHelper= new MydbHelper(this);
        //在EditText中監聽輸入變化
        editText.addTextChangedListener(watcher);
        //查詢全部在ListView中顯示
        myQuery(null,null);
        
    }
    //註冊組件
    private void init()
    {
     listView =(ListView)findViewById(R.id.listView1);
        editText= (EditText)findViewById(R.id.editText1);
        
        
    }
//根據條件在數據庫中模糊查詢 並在ListView中顯示
    private void myQuery(String selection,String[] selectionArgs){
 databases =dbHelper.getReadableDatabase();
 c=databases.query(MydbHelper.TABLE_NAME, null, selection,selectionArgs , null, null,null);
 SimpleCursorAdapter adapter = new SimpleCursorAdapter(getApplicationContext(),android.R.layout.simple_list_item_2, c,new String[]{MydbHelper.WORD,MydbHelper.CHINESE},new int[]{android.R.id.text1,android.R.id.text2});
         
        listView.setAdapter(adapter);
 }
    //EditText中輸入內容監視
    //TextWatcher中重寫的三個方法在EditText中每輸入一個字符都執行一遍
    TextWatcher watcher = new TextWatcher() {
 
 @Override
 public void onTextChanged(CharSequence s, int start, int before, int count) {
         // TODO Auto-generated method stub 
 Log.d("=================", "onTextChanged is called!");
 String selection = MydbHelper.WORD+" LIKE ?";
 String[] selectionArgs= new String[]{s.toString()+"%"};
 myQuery(selection,selectionArgs);
 }
 
 
 @Override
 public void beforeTextChanged(CharSequence s, int start, int count,
 int after) {
 // TODO Auto-generated method stub
 Log.d("===============", "beforTextChanged is called");
 
 }
 
 @Override
 public void afterTextChanged(Editable s) {
 // TODO Auto-generated method stub
 Log.d("=================", "afterTextChanged is called!");
 }
 };
 
}
相關文章
相關標籤/搜索