onKey in activity not invoked

831 Views Asked by At

I want to simulate a series of key events. After a little time searching, I found sendkeyEvent method of objects of BaseInputConnection type. So in onCreate() function of MainActivity class, I send a keyevent three times to a textview, which I binds to this activity.

@Override
protected void onCreate(Bundle savedInstanceState){
  ...
  TextView tv = (TextView) findViewById(R.id.sample_text);
  tv.setText(stringFromJNI);
  tv.setOnKeyListener(this);

  BaseInputConnection mInputConnection = new BaseInputConnection(tv, true);
  //BaseInputConnection mInputConnection = new BaseInputConnection(tv, false);
  KeyEvent kleft = new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT);
  for(int i=0;i<3;i++){
    mInputConnection.sendKeyEvent(kleft);
    Log.d(TAG, "keyevent sent");
  }
}

MainActivity class implements the interface OnKeyListener.

@Override
public boolean OnKey(View v, int keyCode, KeyEvent){
  Log.d(TAG, "OnKey starts.");
  if(event.getKeyCode()==KeyEvent.KEYCODE_DPAD_LEFT && event.getAction()==KeyEvent.ACTION_DOWN){
    Log.d(TAG, "key left.");
    return true;
  }
  return false;
}

After checking the output of logcat, I find that "keyevent sent" was printend three times, which means that keyevents were sent. But there was no "OnKey starts". Why OnKey() function was not invoked?

3

There are 3 best solutions below

0
Pabel On

¿ Can you try use this method ? onKeyDown works for me

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
 switch (keyCode) {
 case KeyEvent.KEYCODE_MENU:
    /* Sample for handling the Menu button globally */
    return true;
 }
 return false;
} 
2
Sharath kumar On

OnKeyListener works only with hardware keyboards". Check this link

https://developer.android.com/reference/android/view/View.OnKeyListener.html

Instead use TextWatchListener for text change of the textView.

tv.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

        }

        @Override
        public void afterTextChanged(Editable editable) {

        }
    });
2
Ghulam Moinul Quadir On

Try this instead of onKey()

    @Override
            public boolean dispatchKeyEvent(KeyEvent event) {
                if(event.getKeyCode()==KeyEvent.KEYCODE_DPAD_LEFT && event.getAction()==KeyEvent.ACTION_DOWN){
                   Log.d(TAG, "key left.");
                   return true;
               }
                return super.dispatchKeyEvent(event);
            }