EditText監聽,根據輸入內容查詢數據并動態更新ListView
Email:chentravelling@163.com
電話簿里有一個很實用的功能,就是根據姓名或者電話號碼搜索聯系人;很多網站或者軟件有回復、評論、注冊等功能,會限制輸入字數,每當用戶輸入一個字數字后,會動態顯示已經輸入的字數或者剩余還能輸入多少數字。在android系統里,我們可以通過對EditText進行監聽,如果內容發生了改變就執行某項操作就行。
- 環境
> IDE:Android Studio
> JDK:1.8
> 系統:win7 64位
- 聲明:
> 1)我查詢數據和適配器是Cursor和SimpleCursorAdapter
> 2)關于ListView顯示數據和動態更新可戳這里《[Cursor記錄集游標、ListView和SimpleCursorAdapter、ListView數據動態更新](http://blog.csdn.net/chentravelling/article/details/50364162)》
- 步驟1:在Activity(繼承ListActivity)中增加全局變量
~~~
private AddressDAO addressDAO;//操作數據庫的類
private SimpleCursorAdapter adapter;//適配器
private Cursor cursor;//記錄集游標
private EditText searchText;//搜索欄
private String condition;//查詢條件
~~~
- 步驟2:在onCreate中為搜索欄添加監聽事件
~~~
//需要先導入
import android.text.TextWatcher;
//然后添加監聽事件
searchText = (EditText)findViewById(R.id.search);
searchText.addTextChangedListener(textWatcher);
~~~
- 步驟3:監聽事件
~~~
TextWatcher textWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//Toast.makeText(ShowAddressActivity.this,"beforeTextChanged ",Toast.LENGTH_SHORT).show();
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//Toast.makeText(ShowAddressActivity.this,"onTextChanged ",Toast.LENGTH_SHORT).show();
}
@Override
public void afterTextChanged(Editable s) {
//Toast.makeText(ShowAddressActivity.this,"afterTextChanged ",Toast.LENGTH_SHORT).show();
condition = searchText.getText().toString();
try{
cursor = addressDAO.conditionQuery(condition);
adapter.changeCursor(cursor);
}catch(Exception e){}
// new RefresListR().execute();
}
};
~~~
- 聲明:adapter.changeCursor(Cursor)相當于通知適配器當前的數據集cursor已經改變了,需要刷新ListView了
- 步驟4:查詢數據,才數據庫操作類中增加查詢函數
~~~
//查詢數據:返回的是一個Cursor對象
public Cursor conditionQuery(String condition)
{
String sql;
if(condition.length()>0||!"".equals(condition))
{
sql = "select * from people where name like '%"+condition+"%' or phone like '%"+condition+"%'";
}else
{
sql = "select * from people";
}
//獲取SQLiteDatabase對象實例
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(sql, null);
return cursor;
}
~~~
通過上面4個步驟,基本可以完成在搜索欄根據輸入的文字進行條件查詢,親測了一下。當然可能數據過多的時候,采用這個方法可能會造成讀取時間長的問題,那么最好可以使用后臺線程讀取數據庫,可參考《[Cursor記錄集游標、ListView和SimpleCursorAdapter、ListView數據動態更新](http://blog.csdn.net/chentravelling/article/details/50364162)》。
初學者個人理解,難免有誤,歡迎指正。