12

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.

Actually, I need a method like

void onKeyReceived(int keyCode)
{
  // here I would like to append the keyCode to EditText, I know how to add a visible character, but what about some special keys, like arrow key, backspace key.
}
Andrew Panasiuk
  • 626
  • 1
  • 8
  • 17
virsir
  • 15,159
  • 25
  • 75
  • 109

10 Answers10

28

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.

Torben
  • 3,805
  • 26
  • 31
  • How can you send Ctrl+keys, for example Ctrl+Z? – TechAurelian Feb 27 '19 at 09:57
  • 1
    "Ctrl+Z" is not a key, but a key combination. You would simulate it by sending the events you produce when using the actual keyboard in correct order: ACTION_DOWN for Ctrl, ACTION_DOWN for Z, ACTION_UP for Z, ACTION_UP for Ctrl (though I don't think the order of the ACTION_UP events matters). – Torben Feb 27 '19 at 12:39
  • 1
    Note that if you want to produce the event that is sent by the Shell when it detects the key combination "Ctrl+Z" (SIGTSTP) then there are probably better options for that than simulating the key presses. But that's a completely different topic for a question. – Torben Feb 27 '19 at 12:43
  • Thank you, I've opened a new question on the topic: [Calling the builtin Undo functionality of EditText by sending Ctrl+Z](https://stackoverflow.com/questions/54903249/calling-the-builtin-undo-functionality-of-edittext-by-sending-ctrlz) – TechAurelian Feb 27 '19 at 13:22
7

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.

dave.c
  • 10,910
  • 5
  • 39
  • 62
2

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

Community
  • 1
  • 1
Labeeb Panampullan
  • 34,521
  • 28
  • 94
  • 112
2

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.

100rabh
  • 6,156
  • 5
  • 27
  • 41
1

Check for key events in your activity. for example, this code listens for back keypress:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK))
    {
    finish();
    }
    return super.onKeyDown(keyCode, event);
}
Aman Alam
  • 11,231
  • 7
  • 46
  • 81
1

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.

dave.c
  • 10,910
  • 5
  • 39
  • 62
N-JOY
  • 10,344
  • 7
  • 51
  • 69
  • I do not want to monitor the change of the edit text, but I want to set some char into the edit control especially for some special key like 'backspace' – virsir Jan 24 '11 at 08:14
1

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));
}
Nathan Schwermann
  • 31,285
  • 16
  • 80
  • 91
1

if you want a click listener, the best way to do it is this:

View textfield = findViewById(R.id.textfield);  
textfield .setOnClickListener(new View.OnClickListener() { 
public void onClick(View v) {  
/*your code for the click event here*/ }});

if you want a backspace button, do this:

public void backSpace() {   
EditText textfield = (EditText)findViewById(R.id.textfield);  
    try {  
        textfield.getText().delete(textfield.getSelectionEnd() - 1, textfield.getSelectionStart());  
    } catch (Exception e) {  
        try {  
            textfield.getText().delete(textfield.length() - 1, textfield.length());  
        } catch (Exception myException) {  
        //textfield.getText().delete(textfield.length(), textfield.length() - 1);  
        }  
    }  
}

if you want to append a character in the EditText, do this:

EditText textfield = (EditText)findViewById(R.id.textfield);  
textfield.setText(textfield.getText().concat("112"));
Ephraim
  • 8,352
  • 9
  • 31
  • 48
  • This will not work. Cursor can be anywhere in the edit text and this only removes characters from the end of the text. The OP wants to send a "virtual key press" to the edit text. – Torben Jan 05 '12 at 19:25
  • 1
    this doesn't remove them from the end of the text, this removes them from the beginning of the selection to the end of the selection, and if there is no selection, it removes it from the whatever character is after the cursor. – Ephraim Jan 11 '12 at 16:29
1

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);

Buda Gavril
  • 21,409
  • 40
  • 127
  • 196
  • That only removes text from the end of the string. What if the cursor is in the middle of the string? – Torben Jan 05 '12 at 19:30
1

Take a look at this article: creating-input-method.html. Basically, you can either manually send KeyEvents or you can manually edit and commit text around the cursor in the application's Input View.These are all done via your IME's InputConnection.

Hope this helps,

Harry Joy
  • 58,650
  • 30
  • 162
  • 207