如果我有一个EditText,想监听用户是否按下键盘上的“完成”按钮...我该如何做到呢?
Dinash的回答很好,但并不适用于所有设备。以下代码适用于所有设备。
edittext.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_DONE) {
Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
代码是
final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER) {
Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
这里的“edittext”是文本框的id。
在 Kotlin 中处理完成操作的基本方法是:
edittext.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
// Call onDone result here
true
}
false
}
在主要代码中使用此方法调用edittext.onDone {/*action*/}
。使代码更易读和可维护。
edittext.onDone { submitForm() }
fun EditText.onDone(callback: () -> Unit) {
// These lines optional if you don't want to set in Xml
imeOptions = EditorInfo.IME_ACTION_DONE
maxLines = 1
setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
callback.invoke()
true
}
false
}
}
如果没有在代码中添加,请不要忘记将这些选项添加到您的edittext Xml中
<EditText ...
android:imeOptions="actionDone"
android:inputType="text"/>
inputType="textMultiLine"
,请阅读此帖子。相同的Jone答案,但使用替换的lambda:
etPointCombatFirst.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_DONE) {
Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
});
根据Asad Rao的反馈,我创建了这个KOTLIN扩展函数。
fun TextView.onClickKeyboardDoneButton(funExecute: () -> Unit) {
this.setOnEditorActionListener { _, actionId, _ ->
when (actionId) {
EditorInfo.IME_ACTION_DONE -> {
funExecute.invoke()
true
}
else -> false
}
}
}
使用:
myEditText.onClickKeyboardDoneButton{myFunctionToExecuteWhenUserClickDone()}
最初的回答:
fun EditText.onImeActionDoneClicks(): Observable<Unit> {
return Observable.create { emitter ->
setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
emitter.onNext(Unit)
true
} else {
false
}
}
}
}
compositeDisposable += lastEditText.onImeActionDoneClicks().subscribe {
toast("onImeDoneClicks")
}
这个 Kotlin 版本应该能在所有设备上运行:
最初的回答:
editText.setOnEditorActionListener { _, actionId, _ ->
if (actionId == EditorInfo.IME_ACTION_DONE) {
// Do something
true
} else {
false
}
}