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

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


当前回答

硬件键盘总是产生输入事件,但是软件键盘在单个的lineedittext中返回不同的actionid和null。每当用户在已设置此侦听器的EditText中按下enter键时,此代码就会响应,而不管EditText或键盘类型是什么。

import android.view.inputmethod.EditorInfo;
import android.view.KeyEvent;
import android.widget.TextView.OnEditorActionListener;

listener=new TextView.OnEditorActionListener() {
  @Override
  public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
    if (event==null) {
      if (actionId==EditorInfo.IME_ACTION_DONE);
      // Capture soft enters in a singleLine EditText that is the last EditText.
      else if (actionId==EditorInfo.IME_ACTION_NEXT);
      // Capture soft enters in other singleLine EditTexts
      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.
      else  return true;   // We consume the event when the key is released.  
    }
    else  return false; 
    // We let the system handle it when the listener
    // is triggered by something that wasn't an enter.


    // Code from this point on will execute whenever the user
    // presses enter in an attached view, regardless of position, 
    // keyboard, or singleLine status.

    if (view==multiLineEditText)  multiLineEditText.setText("You pressed enter");
    if (view==singleLineEditText)  singleLineEditText.setText("You pressed next");
    if (view==lastSingleLineEditText)  lastSingleLineEditText.setText("You pressed done");
    return true;   // Consume the event
  }
};

The default appearance of the enter key in singleLine=false gives a bent arrow enter keypad. When singleLine=true in the last EditText the key says DONE, and on the EditTexts before it it says NEXT. By default, this behavior is consistent across all vanilla, android, and google emulators. The scrollHorizontal attribute doesn't make any difference. The null test is important because the response of phones to soft enters is left to the manufacturer and even in the emulators, the vanilla Level 16 emulators respond to long soft enters in multi-line and scrollHorizontal EditTexts with an actionId of NEXT and a null for the event.

其他回答

文本字段上的InputType必须是文本,以便CommonsWare所说的工作。刚刚尝试了所有这些,在试验之前没有inputType,没有任何工作,进入一直注册为软进入。在inputType = text之后,包括setImeLabel在内的所有东西都工作了。

示例:android:inputType="text"

这在LG安卓手机上运行良好。它防止ENTER和其他特殊字符被解释为普通字符。“下一步”或“完成”按钮自动出现,“ENTER”按预期工作。

edit.setInputType(InputType.TYPE_CLASS_TEXT);

我知道这已经有一年了,但我刚刚发现这非常适合EditText。

EditText textin = (EditText) findViewById(R.id.editText1);
textin.setInputType(InputType.TYPE_CLASS_TEXT);

除了文本和空格,它可以阻止任何东西。我不能制表,“返回”(“\n”),或任何东西。

我通过扩展新的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'

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

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