我想知道是否有一种方法来处理用户在输入EditText时按下Enter,就像onSubmit HTML事件。

还想知道是否有一种方法来操纵虚拟键盘,以这样的方式,“完成”按钮被标记为其他的东西(例如“Go”),并在单击时执行特定的动作(再次,像onSubmit)。


当前回答

这将在用户按下返回键时为您提供一个可调用的函数。

fun EditText.setLineBreakListener(onLineBreak: () -> Unit) {
    val lineBreak = "\n"
    doOnTextChanged { text, _, _, _ ->
        val currentText = text.toString()

        // Check if text contains a line break
        if (currentText.contains(lineBreak)) {

            // Uncommenting the lines below will remove the line break from the string
            // and set the cursor back to the end of the line

            // val cleanedString = currentText.replace(lineBreak, "")
            // setText(cleanedString)
            // setSelection(cleanedString.length)

            onLineBreak()
        }
    }
}

使用

editText.setLineBreakListener {
    doSomething()
}

其他回答

添加这些依赖项,应该可以工作:

import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

本页详细描述了如何做到这一点。

https://developer.android.com/training/keyboard-input/style.html

设置android:imeOptions,然后检查onEditorAction中的actionId。因此,如果你设置imeOptions为“actionDone”,那么你会检查“actionId == EditorInfo”。onEditorAction中的IME_ACTION_DONE `。另外,确保设置android:inputType。

如果使用材质设计,将代码放在TextInputEditText中。

下面是上面链接的例子中的EditText:

<EditText
    android:id="@+id/search"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="@string/search_hint"
    android:inputType="text"
    android:imeOptions="actionSend" />

您还可以使用setImeOptions(int)函数以编程方式设置此选项。下面是上面链接的例子中的OnEditorActionListener:

EditText editText = (EditText) findViewById(R.id.search);
editText.setOnEditorActionListener(new OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            sendMessage();
            handled = true;
        }
        return handled;
    }
});

将“txtid”替换为您的EditText ID。

EditText txtinput;
txtinput=findViewById(R.id.txtid)    
txtinput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))     || (actionId == EditorInfo.IME_ACTION_DONE)) {
                
                //Code for the action you want to proceed with.

                InputMethodManager inputManager = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);

                 inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
            return false;
        }
    });

我使用Kotlin创建了一个函数,它可以处理EditText的所有“完成”动作,包括键盘,并且可以修改它,也可以处理其他按键:

private val DEFAULT_ACTIONS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT = arrayListOf(EditorInfo.IME_ACTION_SEND, EditorInfo.IME_ACTION_GO, EditorInfo.IME_ACTION_SEARCH, EditorInfo.IME_ACTION_DONE)
private val DEFAULT_KEYS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT = arrayListOf(KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER)

fun EditText.setOnDoneListener(function: () -> Unit, onKeyListener: OnKeyListener? = null, onEditorActionListener: TextView.OnEditorActionListener? = null,
                               actionsToHandle: Collection<Int> = DEFAULT_ACTIONS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT,
                               keysToHandle: Collection<Int> = DEFAULT_KEYS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT) {
    setOnEditorActionListener { v, actionId, event ->
        if (onEditorActionListener?.onEditorAction(v, actionId, event) == true)
            return@setOnEditorActionListener true
        if (actionsToHandle.contains(actionId)) {
            function.invoke()
            return@setOnEditorActionListener true
        }
        return@setOnEditorActionListener false
    }
    setOnKeyListener { v, keyCode, event ->
        if (onKeyListener?.onKey(v, keyCode, event) == true)
            return@setOnKeyListener true
        if (event.action == KeyEvent.ACTION_DOWN && keysToHandle.contains(keyCode)) {
            function.invoke()
            return@setOnKeyListener true
        }
        return@setOnKeyListener false
    }
}

那么,示例用法:

        editText.setOnDoneListener({
            //do something
        })

至于改变标签,我认为这取决于键盘应用,它通常只在横屏上改变,就像这里写的那样。总之,这个的用法示例:

        editText.imeOptions = EditorInfo.IME_ACTION_DONE
        editText.setImeActionLabel("ASD", editText.imeOptions)

或者,如果你想用XML:

    <EditText
        android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:imeActionLabel="ZZZ" android:imeOptions="actionDone" />

结果(横屏显示):

在xml中,将imeOptions属性添加到editText中

<EditText
    android:id="@+id/edittext_additem"
    ...
    android:imeOptions="actionDone"
    />

然后,在Java代码中,将OnEditorActionListener添加到相同的EditText中

mAddItemEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if(actionId == EditorInfo.IME_ACTION_DONE){
                //do stuff
                return true;
            }
            return false;
        }
    });

下面是解释 imeOptions=actionDone将“actionDone”分配给EnterKey。键盘上的EnterKey将从“Enter”变为“Done”。因此,当按下回车键时,它将触发这个动作,因此您将处理它。