如何在一个多行的 EditTextView 上添加 Done 和 Return 按钮?

程序中有一个 EditTextView,包括 "Done" 按钮和回车键。
问题是 EditTextView 必须是多行的,还要实现 "Done" 按钮。
使用的代码:

<EditText
    android:id="@+id/messageToSend"
    android:layout_width="match_parent"
    android:layout_height="68dp"
    android:gravity="top|left"
    android:hint="@string/messageToSend"
    android:scrollHorizontally="false"
    android:imeOptions="actionDone"
    android:inputType="textImeMultiLine" />

估计是方法用错了,我想输入结束后隐藏了键盘。

该回答引用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,以实现多行文本输入。