问题
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