未调用活动中的onKey

时间:2017-10-17 08:22:03

标签: android android-activity android-view key-events

我想模拟一系列关键事件。经过一段时间的搜索,我找到sendkeyEvent类型的BaseInputConnection对象方法。因此,在onCreate()类的MainActivity函数中,我将一个关键事件发送三次到textview,我将绑定到此活动。

@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类实现接口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;
}

检查logcat的输出后,我发现“keyevent sent”被打印三次,这意味着发送了keyevents。但是没有“OnKey开始”。为什么没有调用OnKey()函数?

3 个答案:

答案 0 :(得分:0)

¿你能尝试使用这种方法吗? onKeyDown 适合我

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

答案 1 :(得分:0)

OnKeyListener仅适用于硬件键盘“。请检查此链接

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

而是使用TextWatchListener进行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 :(得分:0)

尝试使用此代替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);
            }