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!"); } }; }