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

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


当前回答

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

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

其他回答

作为Chad响应的补充(对我来说几乎完美),我发现我需要在KeyEvent操作类型上添加一个检查,以防止代码执行两次(一次在key-up事件上执行,一次在key-down事件上执行)。

if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN)
{
    // your code here
}

有关重复动作事件(按住enter键)的信息,请参见http://developer.android.com/reference/android/view/KeyEvent.html。

完美的工作

public class MainActivity extends AppCompatActivity {  
TextView t;
Button b;
EditText e;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    b = (Button) findViewById(R.id.b);
    e = (EditText) findViewById(R.id.e);

    e.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            if (before == 0 && count == 1 && s.charAt(start) == '\n') {

                b.performClick();
                e.getText().replace(start, start + 1, ""); //remove the <enter>
            }

        }
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
        @Override
        public void afterTextChanged(Editable s) {}
    });

    b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            b.setText("ok");

        }
    });
}

}

完美的工作

好吧,如果这些答案都对你不起作用,你还没生气,我有一个解决办法。 使用AppCompatMultiAutoCompleteTextView(是的!)而不是EditText与以下代码(kotlin)

val filter = InputFilter { source, start, end, _, _, _ ->
        var keepOriginal = true
        val sb = StringBuilder(end - start)
        for (i in start until end) {
            val c = source[i]
            if (c != '\n')
                sb.append(c)
            else {
                keepOriginal = false
                //TODO:WRITE YOUR CODE HERE
            }
        }
        if (keepOriginal) null else {
            if (source is Spanned) {
                val sp = SpannableString(sb)
                TextUtils.copySpansFrom(source, start, sb.length, null, sp, 0)
                sp
            } else {
                sb
            }
        }
    }

appCompatMultiAutoCompleteTextView.filters = arrayOf(filter);

它(可能)适用于所有设备,我在android 4.4和10上测试了它。它在小米中也起作用。 我他妈的♥机器人:)

下面是一个简单的静态函数,您可以将它扔到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;
        }
    };
}

你应该这样做。它也隐藏在Android开发者的样例代码“蓝牙聊天”中。用你自己的变量和方法替换“example”的粗体部分。

首先,把你需要的东西导入到主Activity中,你想让返回按钮做一些特殊的事情:

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

现在,创建一个类型为TextView的变量。OnEditorActionListener作为返回键(这里我使用exampleListener);

TextView.OnEditorActionListener exampleListener = new TextView.OnEditorActionListener(){

然后,您需要告诉侦听器当按下返回按钮时该做什么。它需要知道我们谈论的EditText是什么(这里我使用exampleView),然后它需要知道当按下Enter键时要做什么(这里是example_confirm())。如果这是活动中最后一个或唯一一个EditText,它应该做与提交(或确定,确认,发送,保存等)按钮的onClick方法相同的事情。

public boolean onEditorAction(TextView exampleView, int actionId, KeyEvent event) {
   if (actionId == EditorInfo.IME_NULL  
      && event.getAction() == KeyEvent.ACTION_DOWN) { 
      example_confirm();//match this behavior to your 'Send' (or Confirm) button
   }
   return true;
}

最后,设置监听器(很可能在你的onCreate方法中);

exampleView.setOnEditorActionListener(exampleListener);