Android -处理"Enter"在编辑文本中

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

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

431015 次浏览

我想知道是否有办法 处理用户按输入 while 输入EditText之类的

. onSubmit HTML事件

是的。

也想知道是否有一种方法 操作虚拟键盘 就像“完成”按钮一样 标记其他东西(例如 “Go”)并执行某个动作

.当点击(再次,像onSubmit)

也没错。

你会想要查看android:imeActionIdandroid:imeOptions属性,以及setOnEditorActionListener()方法,所有这些都在TextView上。

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

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

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

首先,把你需要的东西导入到主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);

作为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

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

我知道这已经有一年了,但我刚刚发现这非常适合EditText。

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

除了文本和空格,它可以阻止任何东西。我不能制表,“返回”(“\n”),或任何东西。

硬件键盘总是产生输入事件,但是软件键盘在单个的lineedittext中返回不同的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中输入键的默认外观给出了一个弯曲的箭头输入键盘。当singleLine=true时,在最后一个EditText中,键表示DONE,在它之前的EditText中,键表示NEXT。默认情况下,此行为在所有vanilla、android和谷歌模拟器中是一致的。scrollHorizontal属性没有任何区别。空测试很重要,因为手机对软输入的响应是留给制造商的,甚至在模拟器中,香草级16模拟器响应多行和scrollHorizontal EditTexts中的长软输入,actionId为NEXT,事件为null。

我也有类似的目的。我想解决按下键盘上的“Enter”键(我想自定义)在一个扩展TextView的AutoCompleteTextView。我从上面尝试了不同的解决方案,它们似乎都有效。但是当我在我的设备(带有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;
}
});

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

一个可靠的方式来回应一个<在EditText中包含TextWatcherLocalBroadcastManagerBroadcastReceiver。你需要添加V4支持库来使用LocalBroadcastManager。我使用vogella.com: 7.3“使用LocalBroadcastManager的本地广播事件”教程,因为其完整简洁的代码示例。在onTextChanged中之前在修改之前,修改结束的索引>;当在TextWatcher中,UI 线程忙于更新editText的可编辑对象,所以当UI 线程完成更新editText时,我们发送一个意图来唤醒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

你也可以做到。

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

文本字段上的InputType必须是text,以便CommonsWare所说的工作。刚刚尝试了所有这些,在试验之前没有inputType,没有任何工作,进入一直注册为软进入。在inputType = text之后,包括setImeLabel在内的所有东西都工作了。

例子: android:inputType="text"

这在LG安卓手机上运行良好。它防止ENTER和其他特殊字符被解释为普通字符。NextDone按钮自动出现,ENTER正常工作。

edit.setInputType(InputType.TYPE_CLASS_TEXT);

首先,您必须设置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的文本的event:

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

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

在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将“actionDone”分配给EnterKey。键盘上的EnterKey将从“Enter”变为“Done”。所以当按下回车键时,它将触发这个动作,因此你将处理它

完美的工作

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


}
});
}

完美的工作

本页详细描述了如何做到这一点。

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

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

如果使用材质设计,将代码放在TextInputEditText中。

下面是上面链接的例子中的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;
}
});
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" />

这应该可以

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

添加这些依赖项,应该可以工作:

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

这是一个简单的静态函数,你可以把它扔到你的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;
}
};
}
   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;
}
});

这个问题还没有被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应用程序

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

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

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

我使用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
})

至于改变标签,我认为这取决于键盘应用程序,它通常只在横屏上改变,如这里<强> < / >强所写。总之,这个的用法示例:

        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

这将在用户按下返回键时为您提供一个可调用的函数。

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

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

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

取代“txtid"与您的EditText ID。

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

你可以用这种方法

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

你可以看到动作列表在那里

例如:

IME_ACTION_GO

IME_ACTION_SEARCH

IME_ACTION_SEND

好吧,如果这些答案都对你不起作用,你还没有生气,我有一个解决办法。 使用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. 它在小米中也起作用。 我他妈的♥android:)

Kotlin解决方案的反应进入按使用Lambda表达式:

        editText.setOnKeyListener { _, keyCode, event ->
if(keyCode == KeyEvent.KEYCODE_ENTER && event.action==KeyEvent.ACTION_DOWN){
//react to enter press here
}
true
}

不做额外的检查类型的事件将导致这个监听器被调用两次时按一次(一次为ACTION_DOWN,一次为ACTION_UP)

通过扩展新的MaterialAlertDialogBuilder,我为此创建了一个helper类

使用

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

联系我们

代码

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'

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

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

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