How to send key event to an edit text

前端 未结 10 2246
醉酒成梦
醉酒成梦 2021-02-07 20:43

For example, send a backspace key to the edit text control to remove a character or send a char code like 112 to append a character in the edittext control programmatically.

10条回答
  •  别那么骄傲
    2021-02-07 21:47

    Your question is not all that clear, but I think you want to modify/append text to a TextView when certain buttons are pressed. If so, you want a combination of some of the existing answers.

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        (TextView) textView = (TextView) findViewById(R.id.myTextView);
    }
    
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        switch(keyCode) {
        case KeyEvent.KEYCODE_BACK:
            // user pressed the "BACK" key.  Append "_back" to the text
            textView.append("_back");
            return true;
        case KeyEvent.KEYCODE_DEL:
            // user pressed the "BACKSPACE" key.  Append "_del" to the text
            textView.append("_del");
            return true;
        default:
            return super.onKeyDown(keyCode, event);
        }
    }
    

    Whether to return true for each case you have handled (as above) or to always return super.onKeyDown(keyCode, event); after your switch statement will depend on your exact requirements. Check the documentation for the behaviour of onKeyDown

    If, instead of appending text in each case you want to delete a character, or move the cursor, you could do that in each case statement. Have a look at the TextView documentation for the different methods you can call. Also look at the KeyEvent documentation for a list of the keys you can check for.

提交回复
热议问题