[英]onKeyListener not working as i want it to… in android
Currently I am using the following code to set onKeyListener for editText in android. 目前,我正在使用以下代码为Android中的editText设置onKeyListener。
final EditText etSearch = (EditText) findViewById(R.id.editText3search);
etSearch.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
MyDbHelper mydbhelper2 = new MyDbHelper(MainActivity.this);
Course[] abc = mydbhelper2.query_searchByCourseName(etSearch.getText().toString());
CourseAdapter cadptrSearch = new CourseAdapter(MainActivity.this, R.layout.list_course_row,abc);
ListView lvSearch = (ListView) findViewById(R.id.list);
lvSearch.setAdapter(cadptrSearch);
return false;
}
});
The problem I am facing is that when I type in the editText for searching, the new list doesn't show up instantly... Instead for the listView to change/update I have to press backspace... This backspace triggers the search in db and the listview changes its contents according to the data entered in edit text. 我面临的问题是,当我输入editText进行搜索时,新列表不会立即显示出来。为了更改/更新listView,我必须按退格键。此退格键触发搜索db和listview根据在编辑文本中输入的数据更改其内容。 I want search results to appear as soon I press any key.
我希望只要按任意键就可以显示搜索结果。 How to do this?
这个怎么做?
Thanks. 谢谢。
Option 1: 选项1:
Use getAction() to determine when any key(excluding the back key) is pressed like this: 使用getAction()确定何时按下任何键(不包括返回键),如下所示:
etSearch.setOnKeyListener(new OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode != KeyEvent.KEYCODE_BACK){
MyDbHelper mydbhelper2 = new MyDbHelper(MainActivity.this);
Course[] abc = mydbhelper2.query_searchByCourseName(etSearch.getText().toString());
CourseAdapter cadptrSearch = new CourseAdapter(MainActivity.this, R.layout.list_course_row,abc);
ListView lvSearch = (ListView) findViewById(R.id.list);
lvSearch.setAdapter(cadptrSearch);
}
return false;
}
});
If that fails, then you're dealing with a soft keyboard issue so try Option 2: 如果失败,那么您正在处理软键盘问题,因此请尝试选择2:
Option 2: Use a text watcher to handle text changed events: 选项2:使用文本观察器来处理文本更改的事件:
etSearch.addTextChangedListener(new TextWatcher () {
public void afterTextChanged(Editable s) {
if(s.length() > 0){
MyDbHelper mydbhelper2 = new MyDbHelper(MainActivity.this);
Course[] abc = mydbhelper2.query_searchByCourseName(etSearch.getText().toString());
CourseAdapter cadptrSearch = new CourseAdapter(MainActivity.this, R.layout.list_course_row,abc);
ListView lvSearch = (ListView) findViewById(R.id.list);
lvSearch.setAdapter(cadptrSearch);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.