如何在Android上捕获KeyEvents?

时间:2012-02-14 12:47:00

标签: android keyevent

我需要在EditText上听取事件

  1. 当用户开始输入
  2. 当焦点丢失时
  3. 我尝试过这个并不起作用。我弄错了什么?

    etTo.setOnKeyListener(new OnKeyListener(){
    
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if(event.getAction() ==KeyEvent.ACTION_DOWN){
                etTo.setText("");
            }
        return false;
        }           
    });
    

2 个答案:

答案 0 :(得分:1)

对于第一个你可以试试这个:

   myEditText.addTextChangedListener(new TextWatcher() {
 public void afterTextChanged(Editable s) {
   //do something
}

  public void beforeTextChanged(CharSequence s, int start, int count, int after){
   //do something
 }

public void onTextChanged(CharSequence s, int start, int before, int count) { 
   //do something
}
});

第二个试试这个:

     myEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {

            yourcalc();

            return true;
        }
        return false;
    }
});

答案 1 :(得分:1)

尝试使用

etTo.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                // TODO Auto-generated method stub

            }
        });

用于检查焦点和

etTo.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO user start to typing text

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO cursor is into the EditText

            }

            @Override
            public void afterTextChanged(Editable arg0) {
                // TODO Auto-generated method stub

            }
        });