该回答引用ChatGPT
要在输入结束后隐藏键盘并实现 "Done" 按钮,可以使用以下代码:
在 XML 中:
<EditText
android:id="@+id/messageToSend"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="top|left"
android:hint="@string/messageToSend"
android:inputType="textMultiLine"
android:maxLines="5"
android:scrollHorizontally="false"
android:imeOptions="actionDone" />
在 Java 中:
EditText messageToSend = findViewById(R.id.messageToSend);
messageToSend.setHorizontallyScrolling(false);
messageToSend.setMaxLines(Integer.MAX_VALUE);
messageToSend.setOnEditorActionListener((textView, actionId, keyEvent) -> {
if (actionId == EditorInfo.IME_ACTION_DONE) {
// 隐藏键盘
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
// 处理 "Done" 操作
doSomething();
return true;
}
return false;
});
这里的关键是使用 setOnEditorActionListener 方法来监听 "Done" 操作,并在监听器中添加隐藏键盘和处理操作的逻辑。另外,需要设置 EditText 的最大行数为 Integer.MAX_VALUE,以实现多行文本输入。