Android onkey - dispatchKeyEvent not firing

跟風遠走 提交于 2019-12-23 09:49:37

问题


well, I've tried all the solutions I could find on stackoverflow and in other places, but the end result hasn't changed one bit: the only key that triggers the onKey event or the dispatchKeyEvent is the enter key on the virtual keyboard, and only if pressed twice. I cannot intercept any other key (there's a breakpoint at the top of the event and eclipse never stops on it, except for in case of the aforementioned enter). Beheaviour is the same on both emulator and real device. Any ideas? Thank you in advance My code atm looks like this:

public class ChatWindow {

 @Override
public void onCreate(Bundle savedInstanceState) {
    //...
    setSendText();
            //...
}

    private void setUserInput() {
    Intent i = getIntent();
    mChatInput = (EditText) findViewById(R.id.UsrInput);
    if (i.hasExtra(INTENT_EXTRA_MESSAGE)) {
        mChatInput.setText(i.getExtras().getString(INTENT_EXTRA_MESSAGE));
    }
    mChatInput.setFocusable(true);
    mChatInput.requestFocus();
    mChatInput.setFocusableInTouchMode(true);

    mChatInput.addTextChangedListener(new TextWatcher() {

        public void  afterTextChanged (Editable s){ 
            Log.d(TAG, "afterTextChanged"); 
            if (mChatInput.getText().length() >= 1) {
                mChatInput.addTextChangedListener(this);
                //mChatInput.setOnKeyListener(this);
                //mChatInput.dispatchKeyEvent(this);
                mSendButton.setEnabled(true);       
            }
                    else 
                       mSendButton.setEnabled(false);
            } 

                    public void  beforeTextChanged  (CharSequence s, int start, int 
                    count, int after)
            { 
                    Log.d(TAG, "beforeTextChanged"); 
            } 

                    public void  onTextChanged  (CharSequence s, int start, int before, 
                    int count) 
            { 
                    Log.d(TAG, s.toString()); 
            }


         }); 

}
}

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
//THIS HERE IS NEVER FIRED UNLESS THE ENTER KEY IS CLICKED TWICE    
    if (event.getAction() == KeyEvent.ACTION_DOWN 
            && event.getKeyCode()==KeyEvent.KEYCODE_ENTER) {
    sendMessageIfNotNull(); 
return true;
}

    return false;
}

回答1:


dispatchKeyEvent will work only when the activity has focus



来源:https://stackoverflow.com/questions/12092438/android-onkey-dispatchkeyevent-not-firing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!