onKeyListener无法工作,因为我想要它...在android中

时间:2014-03-18 22:21:30

标签: android listview android-listview

目前我正在使用以下代码为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;
            }
        });

我面临的问题是当我输入editText进行搜索时,新列表不会立即显示...而不是listView要更改/更新我必须按退格键...退格触发db中的搜索,listview根据编辑文本中输入的数据更改其内容。我希望在按任意键后立即显示搜索结果。怎么做?

感谢。

1 个答案:

答案 0 :(得分:1)

选项1:

使用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;
                    }
                });

如果失败,那么您正在处理软键盘问题,请尝试选项2:

选项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
        }

    });