Android - 在EditText中处理“Enter”

时间:2009-09-28 23:27:56

标签: android android-edittext textview

我想知道在键入EditText时是否有办法处理用户按 Enter ,类似onSubmit HTML事件。

还想知道是否有办法操纵虚拟键盘,使“完成”按钮标记为其他东西(例如“Go”)并在点击时执行某个操作(再次,如onSubmit)。

33 个答案:

答案 0 :(得分:351)

  

我想知道是否有办法   处理用户按 Enter   输入EditText,类似于   onSubmit HTML事件。

是。

  

还想知道是否有办法   操纵虚拟键盘   这样一种“完成”按钮的方式   标记别的东西(例如   “去”)并执行某个动作   点击时(再次,像onSubmit)。

也是。

您需要在TextView上查看android:imeActionIdandroid:imeOptions属性以及setOnEditorActionListener()方法。

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

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

答案 1 :(得分:228)

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

答案 2 :(得分:209)

这是你做的。它也隐藏在Android Developer的示例代码“蓝牙聊天”中。将“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()< /强>)。如果这是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;
}

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

exampleView.setOnEditorActionListener(exampleListener);

答案 3 :(得分:33)

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

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

答案 4 :(得分:20)

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

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

除了文本和空间外,它可以防止任何事情。我无法选项卡,“返回”(“\ n”)或任何其他内容。

答案 5 :(得分:17)

此页面详细描述了如何执行此操作。

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

设置android:imeOptions,然后只需检查onEditorAction中的actionId即可。因此,如果您将imeOptions设置为&#39; actionDone&#39;然后你会检查&#39; actionId == EditorInfo.IME_ACTION_DONE&#39;在onEditorAction中。另外,请确保设置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;
    }
});

答案 6 :(得分:15)

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

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

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

答案 7 :(得分:15)

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

所以这是我的解决方案:

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

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

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

答案 8 :(得分:11)

在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将分配&#34; actionDone&#34;到EnterKey。键盘上的EnterKey将改变为&#34; Enter&#34;到&#34;完成&#34;。因此,当按下Enter键时,它将触发此操作,因此您将处理它。

答案 9 :(得分:7)

你也可以这样做..

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

答案 10 :(得分:5)

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

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

答案 11 :(得分:3)

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

答案 12 :(得分:3)

您可以使用这种方式

editText.setOnEditorActionListener((v, actionId, event) -> {
       if (actionId == EditorInfo.IME_ACTION_DONE) {
          // Do some things      
          return true;
       }
       return false;
});

您可以看到操作列表there

例如:

IME_ACTION_GO

IME_ACTION_SEARCH

IME_ACTION_SEND

答案 13 :(得分:3)

这应该有效

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

答案 14 :(得分:3)

首先,你必须设置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;

答案 15 :(得分:3)

完美运作

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

        }
    });
}

}

完美运作

答案 16 :(得分:2)

这适用于LG Android手机。它可以防止ENTER和其他特殊字符被解释为普通字符。 <{1}}或Next按钮自动显示,Done按预期工作。

ENTER

答案 17 :(得分:2)

使用Kotlin,我已经创建了一个函数,用于处理EditText的各种“完成”式动作,包括键盘,并且可以修改它,也可以根据需要处理其他键:

private val DEFAULT_ACTIONS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT = arrayListOf(EditorInfo.IME_ACTION_SEND, EditorInfo.IME_ACTION_GO, EditorInfo.IME_ACTION_SEARCH, EditorInfo.IME_ACTION_DONE)
private val DEFAULT_KEYS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT = arrayListOf(KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER)

fun EditText.setOnDoneListener(function: () -> Unit, onKeyListener: OnKeyListener? = null, onEditorActionListener: TextView.OnEditorActionListener? = null,
                               actionsToHandle: Collection<Int> = DEFAULT_ACTIONS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT,
                               keysToHandle: Collection<Int> = DEFAULT_KEYS_TO_HANDLE_AS_DONE_FOR_EDIT_TEXT) {
    setOnEditorActionListener { v, actionId, event ->
        if (onEditorActionListener?.onEditorAction(v, actionId, event) == true)
            return@setOnEditorActionListener true
        if (actionsToHandle.contains(actionId)) {
            function.invoke()
            return@setOnEditorActionListener true
        }
        return@setOnEditorActionListener false
    }
    setOnKeyListener { v, keyCode, event ->
        if (onKeyListener?.onKey(v, keyCode, event) == true)
            return@setOnKeyListener true
        if (event.action == KeyEvent.ACTION_DOWN && keysToHandle.contains(keyCode)) {
            function.invoke()
            return@setOnKeyListener true
        }
        return@setOnKeyListener false
    }
}

因此,示例用法:

        editText.setOnDoneListener({
            //do something
        })

关于更改标签,我认为它取决于键盘应用程序,并且通常仅根据横向here进行更改。无论如何,示例用法如下:

        editText.imeOptions = EditorInfo.IME_ACTION_DONE
        editText.setImeActionLabel("ASD", editText.imeOptions)

或者,如果要使用XML:

    <EditText
        android:id="@+id/editText" android:layout_width="wrap_content" android:layout_height="wrap_content"
        android:imeActionLabel="ZZZ" android:imeOptions="actionDone" />

结果(以横向显示):

enter image description here

答案 18 :(得分:2)

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

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

                // Put your function here ---!

                return true;

            }
            return false;
        }
    });

答案 19 :(得分:1)

如果您使用数据绑定,请参阅 https://stackoverflow.com/a/52902266/2914140https://stackoverflow.com/a/67933283/2914140

绑定.kt:

@BindingAdapter("onEditorEnterAction")
fun EditText.onEditorEnterAction(callback: OnActionListener?) {
    if (f == 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()
}

layout.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()}" />

答案 20 :(得分:1)

响应&lt; enter&gt;的可靠方式EditText中包含TextWatcherLocalBroadcastManagerBroadcastReceiver。您需要添加v4 support library才能使用LocalBroadcastManager。我使用vogella.com上的教程:7.3“使用LocalBroadcastManager的本地广播事件”,因为它的代码完整简洁。在onTextChanged 之前变更结束时的索引 &gt ;;减去开始。在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

答案 21 :(得分:1)

用您的EditText ID替换“ txtid”。

EditText txtinput;
txtinput=findViewById(R.id.txtid)    
txtinput.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER))     || (actionId == EditorInfo.IME_ACTION_DONE)) {
                
                //Code for the action you want to proceed with.

                InputMethodManager inputManager = (InputMethodManager)
                        getSystemService(Context.INPUT_METHOD_SERVICE);

                 inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
                        InputMethodManager.HIDE_NOT_ALWAYS);
            }
            return false;
        }
    });

答案 22 :(得分:1)

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

答案 23 :(得分:1)

这是一个简单的静态函数,您可以将其放入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;
        }
    };
}

答案 24 :(得分:1)

文本字段上的InputType必须为text,以便CommonsWare可以使用它。刚刚尝试了所有这一切,在试用之前没有输入类型且没有任何效果,Enter保持注册为软输入。在inputType = text之后,包括setImeLabel在内的所有内容都有效。

示例: android:inputType="text"

答案 25 :(得分:0)

关于牛刀的问题尚未回答

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

答案 26 :(得分:0)

科特琳

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
        }

答案 27 :(得分:0)

当用户按下返回键时,这将为您提供可调用的功能。

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

答案 28 :(得分:0)

检测Enter键被按下的最简单方法是:

mPasswordField.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (event!= null) {   // KeyEvent: If triggered by an enter key, this is the event; otherwise, this is null.
                    signIn(mEmailField.getText().toString(), mPasswordField.getText().toString());
                    return true;
                } else {
                    return false;
                }
            }
        });

答案 29 :(得分:0)

添加这些依赖性,它应该有效:

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

答案 30 :(得分:0)

好吧,如果没有答案对您有用并且还没有生气,那么我有解决方案。 使用AppCompatMultiAutoCompleteTextView(yep!)代替带有此代码(kotlin)的EditText

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:CALL YOUR METHOD 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中对其进行了测试。它也可以在xiaomi上使用。 我该死的♥android:)

答案 31 :(得分:0)

Kotlin溶液使用Lambda表达式反应进入印刷机

while(scanFile.hasNext()) { //if this ends up cutting off bottom line, make it a do while loop
        String value = scanFile.next().toLowerCase();
        value = value.replaceAll("[,.]", "");
        parsed.add(value);
    }

不对事件类型进行额外检查将导致一次按下此侦听器两次(一次为ACTION_DOWN,一次为ACTION_UP)

答案 32 :(得分:0)

我为此扩展了新的MaterialAlertDialogBuilder

,从而创建了一个帮助器类

用法

new InputPopupBuilder(context)
        .setInput(R.string.send, 
                R.string.enter_your_message, 
                text -> sendFeedback(text, activity))
        .setTitle(R.string.contact_us)
        .show();

Contact us

代码

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'