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

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


当前回答

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

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;
    }
});

其他回答

在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”。因此,当按下回车键时,它将触发这个动作,因此您将处理它。

下面是一个简单的静态函数,您可以将它扔到Utils或keyboard类中,当用户敲击硬件或软件键盘上的返回键时,它将执行代码。这是@earlcasper精彩回答的修改版

 /**
 * Return a TextView.OnEditorActionListener that will execute code when an enter is pressed on
 * the keyboard.<br>
 * <code>
 *     myTextView.setOnEditorActionListener(Keyboards.onEnterEditorActionListener(new Runnable()->{
 *         Toast.makeText(context,"Enter Pressed",Toast.LENGTH_SHORT).show();
 *     }));
 * </code>
 * @param doOnEnter A Runnable for what to do when the user hits enter
 * @return the TextView.OnEditorActionListener
 */
public static TextView.OnEditorActionListener onEnterEditorActionListener(final Runnable doOnEnter){
    return (__, actionId, event) -> {
        if (event==null) {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                // Capture soft enters in a singleLine EditText that is the last EditText.
                doOnEnter.run();
                return true;
            } else if (actionId==EditorInfo.IME_ACTION_NEXT) {
                // Capture soft enters in other singleLine EditTexts
                doOnEnter.run();
                return true;
            } else {
                return false;  // Let system handle all other null KeyEvents
            }
        } else if (actionId==EditorInfo.IME_NULL) {
            // Capture most soft enters in multi-line EditTexts and all hard enters.
            // They supply a zero actionId and a valid KeyEvent rather than
            // a non-zero actionId and a null event like the previous cases.
            if (event.getAction()==KeyEvent.ACTION_DOWN) {
                // We capture the event when key is first pressed.
                return true;
            } else {
                doOnEnter.run();
                return true;   // We consume the event when the key is released.
            }
        } else {
            // We let the system handle it when the listener
            // is triggered by something that wasn't an enter.
            return false;
        }
    };
}
     password.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if(event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
                submit.performClick();
                return true;
            }
            return false;
        }
    });

对我来说很好 另外隐藏键盘

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId != 0 || event.getAction() == KeyEvent.ACTION_DOWN) {
                // Action
                return true;
            } else {
                return false;
            }
        }
    });

Xml

<EditText
        android:id="@+id/editText2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="@string/password"
        android:imeOptions="actionGo|flagNoFullscreen"
        android:inputType="textPassword"
        android:maxLines="1" />

我通过扩展新的MaterialAlertDialogBuilder创建了一个辅助类

使用

new InputPopupBuilder(context)
        .setInput(R.string.send, 
                R.string.enter_your_message, 
                text -> sendFeedback(text, activity))
        .setTitle(R.string.contact_us)
        .show();

Code

public class InputPopupBuilder extends MaterialAlertDialogBuilder {

    private final Context context;
    private final AppCompatEditText input;

    public InputPopupBuilder(Context context) {
        super(context);
        this.context = context;
        input = new AppCompatEditText(context);
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        setView(input);
    }

    public InputPopupBuilder setInput(int actionLabel, int hint, Callback callback) {
        input.setHint(hint);
        input.setImeActionLabel(context.getString(actionLabel), KeyEvent.KEYCODE_ENTER);
        input.setOnEditorActionListener((TextView.OnEditorActionListener) (v, actionId, event) -> {
            if (actionId == EditorInfo.IME_NULL
                    && event.getAction() == KeyEvent.ACTION_DOWN) {
                Editable text = input.getText();
                if (text != null) {
                    callback.onClick(text.toString());
                    return true;
                }
            }
            return false;
        });

        setPositiveButton(actionLabel, (dialog, which) -> {
            Editable text = input.getText();
            if (text != null) {
                callback.onClick(text.toString());
            }
        });

        return this;
    }

    public InputPopupBuilder setText(String text){
        input.setText(text);
        return this;
    }

    public InputPopupBuilder setInputType(int inputType){
        input.setInputType(inputType);
        return this;
    }

    public interface Callback {
        void onClick(String text);
    }
}

需要

implementation 'com.google.android.material:material:1.3.0-alpha04'