Android-处理EditText中的“ Enter”

这篇博客讨论了如何在Android应用中处理EditText中的'Enter'键事件,类似于HTML的onSubmit事件。文章提到了使用OnEditorActionListener、imeOptions和inputType属性来改变虚拟键盘的'完成'按钮为其他名称,并在点击时执行特定操作。同时,还分享了不同场景下处理Enter键的多种方法,包括使用TextWatcher和BroadcastReceiver。
摘要由CSDN通过智能技术生成

我想知道是否有一种方法可以处理用户在输入EditTextEnter的问题,例如onSubmit HTML事件。

还想知道是否有一种方法可以操纵虚拟键盘,使“完成”按钮标记为其他名称(例如“转到”),并在单击时执行某种动作(再次类似于onSubmit)。


#1楼

硬件键盘总是产生输入事件,但是软件键盘在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
  }
};

在singleLine = false中,Enter键的默认外观为弯曲的Enter键键盘。 当最后一个EditText中的singleLine = true时,键显示DONE,而在它之前的EditTexts上显示NEXT。 默认情况下,此行为在所有普通,Android和Google模拟器中都是一致的。 scrollHorizo​​ntal属性没有任何区别。 空测试很重要,因为电话对软输入的响应留给了制造商,甚至在仿真器中,香草的16级仿真器也对多行和scrollHorizo​​ntal EditTexts中的长软输入做出了响应,其actionId为NEXT,null为null。事件。


#2楼

我想知道是否有一种方法可以处理在键入EditText时按Enter的用户,例如onSubmit HTML事件。

是。

还想知道是否有一种方法可以操纵虚拟键盘,使“完成”按钮标记为其他名称(例如“转到”),并在单击时执行某种动作(再次类似于onSubmit)。

也可以

您将要查看android:imeActionIdandroid:imeOptions属性,以及setOnEditorActionListener()方法,全部位于TextView

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

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

#3楼

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

所以这是我的解决方案:

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

android:inputType="text"

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

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

将一个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;
    }
});

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


#4楼

在EditText中响应<enter>的可靠方法是使用TextWatcherLocalBroadcastManagerBroadcastReceiver 。 您需要添加v4支持库才能使用LocalBroadcastManager。 我使用vogella.com上的教程:7.3“使用LocalBroadcastManager进行本地广播事件”,因为它具有完整的简洁代码示例。 >;minus start. 在onTextChanged中, before是 >;减去开始 。 当在TextWatcher中,UI线程忙于更新editText的可编辑内容时,因此当UI线程完成对editText的更新后,我们将发送一个Intent来唤醒BroadcastReceiver。

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.text.Editable;
//in onCreate:
editText.addTextChangedListener(new TextWatcher() {
  public void onTextChanged
  (CharSequence s, int start, int before, int count) {
    //check if exactly one char was added and it was an <enter>
    if (before==0 && count==1 && s.charAt(start)=='\n') {
    Intent intent=new Intent("enter")
    Integer startInteger=new Integer(start);
    intent.putExtra("Start", startInteger.toString()); // Add data
    mySendBroadcast(intent);
//in the BroadcastReceiver's onReceive:
int start=Integer.parseInt(intent.getStringExtra("Start"));
editText.getText().replace(start, start+1,""); //remove the <enter>
//respond to the <enter> here

#5楼

您也可以做到。

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

#6楼

为了使CommonsWare能够正常工作, text字段上的InputType必须为text 。 只是尝试了所有这些,在尝试之前没有inputType,也没有任何作用,Enter一直注册为软输入。 在inputType = text ,包括setImeLabel在内的所有东西都起作用了。

示例: android:inputType="text"


#7楼

在LG Android手机上可以正常使用。 它可以防止将ENTER和其他特殊字符解释为普通字符。 NextDone按钮将自动出现,并且ENTER按预期工作。

edit.setInputType(InputType.TYPE_CLASS_TEXT);

#8楼

首先,您必须将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);

}

其次,在按键时定义事件,例如,设置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;   

}

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

import android.view.KeyEvent;
import android.view.View.OnKeyListener;
import android.widget.EditText;
import android.widget.TextView;

#9楼

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

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


#10楼

在您的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将为EnterKey分配“ actionDone”。 键盘中的EnterKey将从“ Enter”更改为“ Done”。 因此,当按下Enter键时,它将触发此操作,因此您将对其进行处理。


#11楼

完美地工作

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

        }
    });
}

}

完美地工作


#12楼

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

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" />

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

#13楼

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" />

#14楼

这应该工作

input.addTextChangedListener(new TextWatcher() {

           @Override
           public void afterTextChanged(Editable s) {}

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

           @Override    
           public void onTextChanged(CharSequence s, int start,
             int before, int count) {
               if( -1 != input.getText().toString().indexOf( "\n" ) ){
                   input.setText("Enter was pressed!");
                    }
           }
          });

#15楼

添加这些depencendy,它应该工作:

import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;

#16楼

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

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

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

#17楼

这是一个简单的静态函数,您可以将其放入UtilsKeyboards类中,该类将在用户按下硬件或软件键盘上的回车键时执行代码。 这是@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;
        }
    };
}

#18楼

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

#19楼

Butterknife尚未回答此问题

布局XML

<android.support.design.widget.TextInputLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/some_input_hint">

        <android.support.design.widget.TextInputEditText
            android:id="@+id/textinput"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:imeOptions="actionSend"
            android:inputType="text|textCapSentences|textAutoComplete|textAutoCorrect"/>
    </android.support.design.widget.TextInputLayout>

JAVA APP

@OnEditorAction(R.id.textinput)
boolean onEditorAction(int actionId, KeyEvent key){
    boolean handled = false;
    if (actionId == EditorInfo.IME_ACTION_SEND || (key.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
        //do whatever you want
        handled = true;
    }
    return handled;
}

#20楼

在编辑器中键入此代码,以便它可以导入必要的模块。

 query.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int actionId, KeyEvent keyEvent) {
            if(actionId == EditorInfo.IME_ACTION_DONE
                    || keyEvent.getAction() == KeyEvent.ACTION_DOWN
                        || keyEvent.getAction() == KeyEvent.KEYCODE_ENTER) {

                // Put your function here ---!

                return true;

            }
            return false;
        }
    });

#21楼

科特林

editTextVar?.setOnKeyListener { v, keyCode, event ->
            if((event.action == KeyEvent.ACTION_DOWN)
                && (event.keyCode == KeyEvent.KEYCODE_ENTER)){
                //Do something, such as loadJob()
                loadJob()
                return@setOnKeyListener true
            }

            false
        }

#22楼

就像乍得的响应​​的附录(对我来说效果很好)一样,我发现我需要对KeyEvent操作类型进行检查,以防止我的代码执行两次(一次在键盘上按下,一次在键盘上按下)事件)。

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

http://developer.android.com/reference/android/view/KeyEvent.html的信息关于重复动作事件(按住Enter键)等。


#23楼

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

#24楼

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

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

它可以防止文本和空格以外的任何内容。 我无法制表符,“返回”(“ \\ n”)或其他任何内容。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值