Android - 在EditText中处理"Enter"

Fel*_*lix 433 android textview android-edittext

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

还想知道是否有一种方法可以操作虚拟键盘,使"完成"按钮被标记为其他东西(例如"Go")并在单击时执行某个操作(再次,如onSubmit).

Com*_*are 361

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

是.

还想知道是否有一种方法可以操作虚拟键盘,使"完成"按钮被标记为其他东西(例如"Go")并在单击时执行某个操作(再次,如onSubmit).

也是的.

您将需要查看android:imeActionIdandroid:imeOptions属性以及setOnEditorActionListener()方法TextView.

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

mEditText.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER);
Run Code Online (Sandbox Code Playgroud)

  • (PS EditText扩展了TextView,因此为什么你应该看看属性是在TextView上 - 当我第一次读到最后一句时我做了双重拍摄:)) (25认同)
  • 作为一个说明.并非所有键盘都支持标准的android:imeOptions属性.这真是令人失望.例如,IME_ACTION_DONE定义为6,其中HTC默认键盘(在Incredible,Evo 4G等手机上)返回键定义为0. (15认同)
  • 此外,如果您使用imeOptions确保您还使用inputType ="text"或其他等效项.确保键盘听你的!Nexus1 (13认同)
  • "是的" - 你会比这更具描述性吗?他可能会问如何实施解决方案. (6认同)
  • @AlWang:首先,您的关注领域包含在答案中(请参阅"您将要..."开头).其次,这个答案来自**六年前**,所以人们会认为OP的问题已经解决了.毕竟,OP接受了答案. (3认同)
  • 提示:使用`actionId == EditorInfo.IME_ACTION_SEND || event.getKeyCode()== KeyEvent.KEYCODE_ENTER && event.getAction()== KeyEvent.ACTION_DOWN`用于检测发送和输入密钥. (3认同)
  • 当这个答案完全没有提供代码来展示如何实际实现所需的操作时,为什么它会获得如此多的赞成票?任何人都可以从 Android 文档中复制和粘贴,而无需真正理解。这个答案不完整并且没有帮助。 (3认同)
  • @CommonsWare我厌倦了使用mEditText.setImeActionLabel("自定义文本",KeyEvent.KEYCODE_ENTER)更改IME操作标签; 我仍然只看到输入按钮的图标... (2认同)

Jar*_*Law 252

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;
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 对CommonsWare没有任何冒犯,但是他的RTFM答案并不比这个简单的例子更有用,它显示了如何做到这一点.谢谢! (5认同)
  • 出于某种原因,当我在我的编辑文本中单击“输入”时,整个编辑文本向下移动......我该如何解决这个问题? (2认同)
  • @RuchirBaronia 将 android:maxLines="1" 添加到您的 EditText。您的 EditText 不是“向下移动”,而是在输入的文本中插入换行符。将 maxLines 设置为 1 可防止插入换行符。 (2认同)
  • 此解决方案仅适用于硬件键盘,不适用于软/虚拟键盘.如果您依赖它,那么对于没有连接键盘的用户,您的应用程序将被破坏. (2认同)
  • @AutonomousApps,我经常看到 CommonsWare 的回答。他很幸运从 2009 年开始回答,那时 Android 开始了。通常是“是”、“否”、“不可能”等,通常没有代码。他的回答现在通常已经过时,所以我尽量不遵循他的建议。 (2认同)

Cha*_*ock 213

这是你做的.它也隐藏在Android Developer的示例代码"蓝牙聊天"中.用您自己的变量和方法替换说"example"的粗体部分.

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

import android.view.inputmethod.EditorInfo;
import android.widget.TextView;
import android.view.KeyEvent;
Run Code Online (Sandbox Code Playgroud)

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

TextView.OnEditorActionListener exampleListener = new TextView.OnEditorActionListener(){
Run Code Online (Sandbox Code Playgroud)

然后,您需要告诉听众有关按下返回按钮时要执行的操作的两件事.它需要知道我们正在谈论的EditText(这里我使用exampleView),然后它需要知道当按下Enter键时该做什么(这里,example_confirm()).如果这是您的Activity中的最后一个或唯一的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;
}
Run Code Online (Sandbox Code Playgroud)

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

exampleView.setOnEditorActionListener(exampleListener);
Run Code Online (Sandbox Code Playgroud)

  • 很好,我使用了EditorInfo.IME_ACTION_SEND,我在XML上有android:imeOptions ="actionSend". (20认同)
  • 通常最好在`KeyEvent.ACTION_UP`上执行操作.为了使其工作,您需要首先使用`ACTION_DOWN`事件:`if(actionId == EditorInfo.IME_NULL && event.getAction()== KeyEvent.ACTION_DOWN){return true; }`.然后你可以检查`ACTION_UP`事件并执行动作(类似于上面的答案).如果不使用`ACTION_DOWN`事件,则不会为`ACTION_UP`调用`onEditorAction`. (3认同)
  • 这对我有用:`if(event.getKeyCode()== KeyEvent.KEYCODE_ENTER && event.getAction()== KeyEvent.ACTION_DOWN){...}` - 无法获得任何其他方法工作 (2认同)

ear*_*per 36

硬件键盘总是产生输入事件,但软件键盘在singleLine EditTexts中返回不同的actionID和null.无论EditText或键盘类型如何,每次用户按下此侦听器已设置的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
  }
};
Run Code Online (Sandbox Code Playgroud)

在singleLine = false中输入键的默认外观给出一个弯曲的箭头输入键盘.当最后一个EditText中的singleLine = true时,键表示DONE,而在之前的EditTexts上表示NEXT.默认情况下,此行为在所有vanilla,android和Google模拟器中都是一致的.scrollHorizo​​ntal属性没有任何区别.空值测试非常重要,因为手机对软输入的响应留给了制造商,即使在模拟器中,vanilla Level 16仿真器也会响应多行中的长软输入和scrollHorizo​​ntal EditTexts,其actionId为NEXT,为null事件.


Mik*_*ike 22

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

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

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

这是上面链接的示例中的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" />
Run Code Online (Sandbox Code Playgroud)

您也可以使用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;
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢,我想这应该是这个用例的默认/接受的答案(处理 EditText 上的输入/提交) (2认同)

小智 21

我知道这已经有一年了,但我发现这对EditText非常有效.

EditText textin = (EditText) findViewById(R.id.editText1);
textin.setInputType(InputType.TYPE_CLASS_TEXT);
Run Code Online (Sandbox Code Playgroud)

除了文本和空间之外,它可以防止任 我无法标签,"返回"("\n")或其他任何东西.


小智 16

就像对Chad的回复(对我来说几乎完美无缺)的附录一样,我发现我需要在KeyEvent动作类型上添加一个检查,以防止我的代码执行两次(一次在键盘上,一次在键盘上)事件).

if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_DOWN)
{
    // your code here
}
Run Code Online (Sandbox Code Playgroud)

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


kao*_*ick 16

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

所以这是我的解决方案:

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

android:inputType="text"
Run Code Online (Sandbox Code Playgroud)

自定义键盘上"Enter"键的标签:

myTextView.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER);
Run Code Online (Sandbox Code Playgroud)

将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;
    }
});
Run Code Online (Sandbox Code Playgroud)

我希望这可以帮助别人避免我遇到的问题,因为他们差点让我疯狂.

  • 你的IF不正确.使用:'event.getKeyCode()== KeyEvent.KEYCODE_ENTER' (3认同)

Raj*_*Raj 14

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

<EditText
    android:id="@+id/edittext_additem"
    ...
    android:imeOptions="actionDone"
    />
Run Code Online (Sandbox Code Playgroud)

然后,在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;
        }
    });
Run Code Online (Sandbox Code Playgroud)

以下是解释 - imeOptions = actionDone将"actionDone"分配给EnterKey.键盘中的EnterKey将从"Enter"更改为"Done".因此,当按下Enter键时,它将触发此操作,因此您将处理它.


Xar*_*mer 8

你也可以这样做..

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;
        }
    });
Run Code Online (Sandbox Code Playgroud)


Coo*_*ind 7

如果您使用 DataBinding,请参阅/sf/answers/3703158651//sf/answers/4755329841/

绑定.kt:

@BindingAdapter("onEditorEnterAction")
fun EditText.onEditorEnterAction(callback: OnActionListener?) {
    if (callback == null) setOnEditorActionListener(null)
    else setOnEditorActionListener { v, actionId, event ->
        val imeAction = when (actionId) {
            EditorInfo.IME_ACTION_DONE,
            EditorInfo.IME_ACTION_SEND,
            EditorInfo.IME_ACTION_GO -> true
            else -> false
        }

        val keydownEvent = event?.keyCode == KeyEvent.KEYCODE_ENTER 
            && event.action == KeyEvent.ACTION_DOWN

        if (imeAction or keydownEvent) {
            callback.enterPressed()
            return@setOnEditorActionListener true
        }
        return@setOnEditorActionListener false
    }
}

interface OnActionListener {
    fun enterPressed()
}
Run Code Online (Sandbox Code Playgroud)

布局.xml:

<data>
    <variable
        name="viewModel"
        type="YourViewModel" />
</data>    

<EditText
    android:imeOptions="actionDone|actionSend|actionGo"
    android:singleLine="true"
    android:text="@={viewModel.message}"
    app:onEditorEnterAction="@{() -> viewModel.send()}" />
Run Code Online (Sandbox Code Playgroud)


Vla*_*lad 6

     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;
        }
    });
Run Code Online (Sandbox Code Playgroud)

对我来说工作非常好
另外隐藏键盘


Lif*_*Hot 5

首先,您必须将EditText设置为监听按键

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

    // Set the EditText listens to key press
    EditText edittextproductnumber = (EditText) findViewById(R.id.editTextproductnumber);
    edittextproductnumber.setOnKeyListener(this);

}
Run Code Online (Sandbox Code Playgroud)

其次,在按键时定义事件,例如,设置TextView文本的事件:

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub

 // Listen to "Enter" key press
 if ((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER))
 {
     TextView textviewmessage = (TextView) findViewById(R.id.textViewmessage);
     textviewmessage.setText("You hit 'Enter' key");
     return true;
 }

return false;   

}
Run Code Online (Sandbox Code Playgroud)

最后,不要忘记在顶部导入EditText,TextView,OnKeyListener,KeyEvent:

import android.view.KeyEvent;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;
Run Code Online (Sandbox Code Playgroud)


小智 5

完美地工作

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

        }
    });
}
Run Code Online (Sandbox Code Playgroud)

}

完美地工作


kre*_*ker 5

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;
            }
        }
    });
Run Code Online (Sandbox Code Playgroud)

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" />
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

337254 次

最近记录:

6 年,3 月 前