How to send key event to an edit text

前端 未结 10 2259
醉酒成梦
醉酒成梦 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:25

    to simulate backspace key, just ad code

    editText.setText(editText.getText().substring(0,editText.getText().length()-1))
    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
    

    to simulate adding a character, put the code

    editText.setText(editText.getText() + (char) charCode)
    

    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);

    0 讨论(0)
  • 2021-02-07 21:29

    just use the setText method to do this. If you are wanting to simulate a backspace you could do something like this.

    String curText = mEditText.getText();
    if(!curText.equals("")){
        mEditText.setText(curText.subString(0, curText.length - 1));
    }
    
    0 讨论(0)
  • 2021-02-07 21:31

    I think you need use addTextChangedListener to EditText.
    Refer the answer of EditText input with pattern android and Live editing of users input

    0 讨论(0)
  • 2021-02-07 21:32

    To send a simulated backspace key press to an EditText you have to send both key press and release events. Like this:

    mEditText.dispatchKeyEvent(new KeyEvent(0, 0, KeyEvent.ACTION_DOWN,
        KeyEvent.KEYCODE_DEL, 0));
    mEditText.dispatchKeyEvent(new KeyEvent(0, 0, KeyEvent.ACTION_UP,
        KeyEvent.KEYCODE_DEL, 0));
    

    This can be used to send any other key code, not just delete.

    0 讨论(0)
  • 2021-02-07 21:32

    try implementing TextWatcher interface.

    it has 3 methods which you need to override.

    public void afterTextChanged(Editable s) {
    
        Log.v("afterTextChanged","here");
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    
        Log.v("beforeTextChanged","here");
    }
    
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }
    

    I think this will work.

    0 讨论(0)
  • 2021-02-07 21:37

    virsir , I suppose you are looking for dispatching hard keys programmatically.

    For that you may try dispatch (KeyEvent.Callback receiver, KeyEvent.DispatcherState state, Object target) with an example at Back and other hard keys: three stories

    Hope that helps.

    0 讨论(0)
提交回复
热议问题