好吧,我已经尝试了所有我可以在stackoverflow和其他地方找到的解决方案,但是最终结果并没有改变一位:触发onKey事件或dispatchKeyEvent的唯一键是虚拟键盘上的Enter键,并且仅在按下两次的情况下。我无法截获其他任何键(事件的开头有一个断点,并且eclipse永不停止,除非上述回车除外)。行为在模拟器和真实设备上都是相同的。有任何想法吗?先感谢您
我的代码atm看起来像这样:
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;
}
最佳答案
只有 Activity 具有焦点时,才能使用dispatchKeyEvent
关于Android onkey-dispatchKeyEvent不触发,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/12092438/