问题
I want to add a functionality on click of "enter" key of Google's keyboard without vanquishing the default newline characteristic. I have used OnKeyListener but it is not working.
EditText edittext = (EditText) findViewById(R.id.user_query);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode ==KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) {
//here i want to print numbers with next line in edit text
return true;
}
return false;
}
});
The same code is working with other keyboards.
回答1:
As stated here
Interface definition for a callback to be invoked when a hardware key event is dispatched to this view. The callback will be invoked before the key event is given to the view. This is only useful for hardware keyboards; a software input method has no obligation to trigger this listener.
And the most safe bet would be to use addTextChangedListener in your case like below
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//here is your code
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
来源:https://stackoverflow.com/questions/39375467/enter-key-listener-for-google-keyboard-is-not-working