如何从EditText软键盘获取关键事件?

时间:2013-10-02 15:38:06

标签: android android-edittext android-softkeyboard keylistener keyevent

我知道如何从物理键盘获取KeyEvent,但我如何从软键盘获取它们?

此代码不适用于软键盘:

editText.setOnKeyListener(new View.OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        Toast.makeText(this, Integer.toString(keyCode), Toast.LENGTH_SHORT)
        return false;
    }
});

2 个答案:

答案 0 :(得分:1)

也许您需要TextChangedListener(或将其用作替代方法):

TextWatcher textWatcher = new TextWatcher() {
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }
    public void onTextChanged(CharSequence s, int start, int before,int count) {        
    }
    public void afterTextChanged(Editable s) {                   
    }       
};
editText.addTextChangedListener(textWatcher);

答案 1 :(得分:0)

试试这个

public void onCreate(Bundle savedInstanceState) {
    ...
    etField =(EditText)findViewById(R.id.your_edit_text);

    etField.setOnKeyListener(new OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
             // register the text when "enter" is pressed
             if (event.getAction() == KeyEvent.ACTION_DOWN 
             || event.getAction() == KeyEvent.ACTION_UP ) {
             int timesPressed = event.getRepeatCount();
             //do something
        }
    });
}

OR

EditText.addTextChangedListener(new TextWatcher(){
   //do something
})