Android - 在 EditText 中处理“Enter”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1489852/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 03:08:14  来源:igfitidea点击:

Android - Handle "Enter" in an EditText

androidandroid-edittexttextview

提问by Felix

I am wondering if there is a way to handle the user pressing Enterwhile typing in an EditText, something like the onSubmit HTML event.

我想知道是否有办法处理用户Enter在输入 时按下的问题EditText,例如 onSubmit HTML 事件。

Also wondering if there is a way to manipulate the virtual keyboard in such a way that the "Done" button is labeled something else (for example "Go") and performs a certain action when clicked (again, like onSubmit).

还想知道是否有一种方法可以操纵虚拟键盘,使“完成”按钮标记为其他内容(例如“开始”)并在单击时执行特定操作(再次,例如 onSubmit)。

采纳答案by CommonsWare

I am wondering if there is a way to handle the user pressing Enterwhile typing in an EditText, something like the onSubmit HTML event.

我想知道是否有办法处理用户Enter在输入 EditText 时按下的按钮,例如 onSubmit HTML 事件。

Yes.

是的。

Also wondering if there is a way to manipulate the virtual keyboard in such a way that the "Done" button is labeled something else (for example "Go") and performs a certain action when clicked (again, like onSubmit).

还想知道是否有一种方法可以操纵虚拟键盘,使“完成”按钮标记为其他内容(例如“开始”)并在单击时执行特定操作(再次,例如 onSubmit)。

Also yes.

也是。

You will want to look at the android:imeActionIdand android:imeOptionsattributes, plus the setOnEditorActionListener()method, all on TextView.

您将需要查看android:imeActionIdandroid:imeOptions属性以及setOnEditorActionListener()方法,所有这些都在 上TextView

For changing the text of the "Done" button to a custom string, use:

要将“完成”按钮的文本更改为自定义字符串,请使用:

mEditText.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER);

回答by Jarod DY Law

final EditText edittext = (EditText) findViewById(R.id.edittext);
edittext.setOnKeyListener(new OnKeyListener() {
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        // If the event is a key-down event on the "enter" button
        if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
            (keyCode == KeyEvent.KEYCODE_ENTER)) {
          // Perform action on key press
          Toast.makeText(HelloFormStuff.this, edittext.getText(), Toast.LENGTH_SHORT).show();
          return true;
        }
        return false;
    }
});

回答by Chad Hedgcock

Here's what you do. It's also hidden in the Android Developer's sample code 'Bluetooth Chat'. Replace the bold parts that say "example"with your own variables and methods.

这就是你要做的。它也隐藏在 Android 开发人员的示例代码“蓝牙聊天”中。用您自己的变量和方法替换显示“示例”的粗体部分。

First, import what you need into the main Activity where you want the return button to do something special:

首先,将您需要的内容导入到您希望返回按钮执行一些特殊操作的主 Activity 中:

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

Now, make a variable of type TextView.OnEditorActionListener for your return key (here I use exampleListener);

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

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

Then you need to tell the listener two things about what to do when the return button is pressed. It needs to know what EditText we're talking about (here I use exampleView), and then it needs to know what to do when the Enter key is pressed (here, example_confirm()). If this is the last or only EditText in your Activity, it should do the same thing as the onClick method for your Submit (or OK, Confirm, Send, Save, etc) button.

然后,您需要告诉侦听器有关按下返回按钮时要执行的操作的两件事。它需要知道我们在谈论什么 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;
}

Finally, set the listener (most likely in your onCreate method);

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

exampleView.setOnEditorActionListener(exampleListener);

回答by earlcasper

Hardware keyboards always yield enter events, but software keyboards return different actionIDs and nulls in singleLine EditTexts. This code responds every time the user presses enter in an EditText that this listener has been set to, regardless of EditText or keyboard type.

硬件键盘总是产生输入事件,但软件键盘在 singleLine EditTexts 中返回不同的 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.

singleLine=false 中输入键的默认外观给出了一个弯曲的箭头输入键盘。当最后一个 EditText 中的 singleLine=true 时,键显示 DONE,在它之前的 EditTexts 上显示 NEXT。默认情况下,此行为在所有 vanilla、android 和 google 模拟器中都是一致的。scrollHorizo​​ntal 属性没有任何区别。null 测试很重要,因为手机对软输入的响应是由制造商决定的,即使在模拟器中,vanilla Level 16 模拟器也会响应多行和 scrollHorizo​​ntal EditTexts 中的长软输入,actionId 为 NEXT 并且为 null事件。

回答by Mike

This page describes exactly how to do this.

此页面准确描述了如何执行此操作。

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

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

Set the android:imeOptionsthen you just check the actionIdin onEditorAction. So if you set imeOptions to 'actionDone' then you would check for 'actionId == EditorInfo.IME_ACTION_DONE' in onEditorAction. Also, make sure to set the android:inputType.

设置android:imeOptions然后你只需检查onEditorAction中的 actionId。因此,如果您将 imeOptions 设置为“actionDone”,那么您将在 onEditorAction 中检查“actionId == EditorInfo.IME_ACTION_DONE”。另外,请确保设置 android:inputType。

Here's the EditText from the example linked above:

这是上面链接的示例中的 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" />

You can also set this programmatically using the setImeOptions(int)function. Here's the OnEditorActionListener from the example linked above:

您还可以使用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;
    }
});

回答by Newbie

I know this is a year old, but I just discovered this works perfectly for an EditText.

我知道这是一岁了,但我刚刚发现这对 EditText 非常有效。

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

It prevents anything but text and space. I could not tab, "return" ("\n"), or anything.

它可以防止除文本和空格之外的任何内容。我无法使用 Tab、“返回”(“\n”)或任何东西。

回答by kaolick

I had a similar purpose. I wanted to resolve pressing the "Enter" key on the keyboard (which I wanted to customize) in an AutoCompleteTextView which extends TextView. I tried different solutions from above and they seemed to work. BUT I experienced some problems when I switched the input type on my device (Nexus 4 with AOKP ROM) from SwiftKey 3 (where it worked perfectly) to the standard Android keyboard (where instead of handling my code from the listener, a new line was entered after pressing the "Enter" key. It took me a while to handle this problem, but I don't know if it will work under all circumstances no matter which input type you use.

我也有类似的目的。我想解决在扩展 TextView 的 AutoCompleteTextView 中按下键盘上的“Enter”键(我想自定义)的问题。我从上面尝试了不同的解决方案,它们似乎有效。但是当我将设备(带有 AOKP ROM 的 Nexus 4)上的输入类型从 SwiftKey 3(它完美地工作)切换到标准的 Android 键盘(而不是从侦听器处理我的代码时,我遇到了一些问题,新的一行是按“Enter”键后输入。我花了一段时间来处理这个问题,但我不知道无论您使用哪种输入类型,它是否都能在所有情况下工作。

So here's my solution:

所以这是我的解决方案:

Set the input type attribute of the TextView in the xml to "text":

将xml中TextView的输入类型属性设置为“text”:

android:inputType="text"

Customize the label of the "Enter" key on the keyboard:

自定义键盘上“回车”键的标签:

myTextView.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER);

Set an OnEditorActionListener to the TextView:

将 OnEditorActionListener 设置为 TextView:

myTextView.setOnEditorActionListener(new OnEditorActionListener()
{
    @Override
    public boolean onEditorAction(TextView v, int actionId,
        KeyEvent event)
    {
    boolean handled = false;
    if (event.getAction() == KeyEvent.KEYCODE_ENTER)
    {
        // Handle pressing "Enter" key here

        handled = true;
    }
    return handled;
    }
});

I hope this can help others to avoid the problems I had, because they almost drove me nuts.

我希望这可以帮助其他人避免我遇到的问题,因为他们几乎把我逼疯了。

回答by kermitology

Just as an addendum to Chad's response (which worked almost perfectly for me), I found that I needed to add a check on the KeyEvent action type to prevent my code executing twice (once on the key-up and once on the key-down event).

正如 Chad 响应的附录(这对我来说几乎完美无缺),我发现我需要添加对 KeyEvent 操作类型的检查,以防止我的代码执行两次(一次在按键上,一次在按键上)事件)。

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

See http://developer.android.com/reference/android/view/KeyEvent.htmlfor info about repeating action events (holding the enter key) etc.

有关重复操作事件(按住 Enter 键)等的信息,请参阅http://developer.android.com/reference/android/view/KeyEvent.html

回答by ARK

In your xml, add the imeOptions attribute to the editText

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

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

Then, in your Java code, add the OnEditorActionListener to the same EditText

然后,在您的 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;
        }
    });

Here is the explanation- The imeOptions=actionDone will assign "actionDone" to the EnterKey. The EnterKey in the keyboard will change from "Enter" to "Done". So when Enter Key is pressed, it will trigger this action and thus you will handle it.

这是解释 - imeOptions=actionDone 将“actionDone”分配给 EnterKey。键盘中的 EnterKey 将从“Enter”变为“Done”。因此,当按下 Enter 键时,它将触发此操作,因此您将对其进行处理。

回答by Jawad Zeb

You can also do it..

你也可以这样做..

editText.setOnKeyListener(new OnKeyListener() {

            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event)
            {
                if (event.getAction() == KeyEvent.ACTION_DOWN
                        && event.getKeyCode() ==       KeyEvent.KEYCODE_ENTER) 
                {
                    Log.i("event", "captured");

                    return false;
                } 

            return false;
        }
    });