Sushan Ghimire
Sushan Ghimire

Reputation: 7567

How to capture KeyEvents on android?

I need to listen to events on a EditText

  1. when users start typing
  2. and when focus is lost

I tried this and it does not work. What have I got it wrong?

etTo.setOnKeyListener(new OnKeyListener(){

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

Upvotes: 2

Views: 833

Answers (2)

Nataliia.dev
Nataliia.dev

Reputation: 2972

Try to use

etTo.setOnFocusChangeListener(new OnFocusChangeListener() {

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

            }
        });

for checking focus and

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

            }
        });

Upvotes: 1

Navdroid
Navdroid

Reputation: 4533

For the first one you could try this:

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

for second one try this:

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

Upvotes: 1

Related Questions