我想知道是否有一种方法来处理用户在输入EditText时按下Enter,就像onSubmit HTML事件。
还想知道是否有一种方法来操纵虚拟键盘,以这样的方式,“完成”按钮被标记为其他的东西(例如“Go”),并在单击时执行特定的动作(再次,像onSubmit)。
我想知道是否有一种方法来处理用户在输入EditText时按下Enter,就像onSubmit HTML事件。
还想知道是否有一种方法来操纵虚拟键盘,以这样的方式,“完成”按钮被标记为其他的东西(例如“Go”),并在单击时执行特定的动作(再次,像onSubmit)。
我想知道是否有办法 处理用户按Enter键时 输入EditText之类的 onSubmit HTML事件。
是的。
也在想有没有办法 操作虚拟键盘 就像“完成”按钮一样 标记其他东西(例如 “Go”)并执行某个动作 当点击(再次,像onSubmit)。
也没错。
你会想看看android:imeActionId和android:imeOptions属性,加上setOnEditorActionListener()方法,所有的TextView。
要将“Done”按钮的文本更改为自定义字符串,请使用:
mEditText.setImeActionLabel("Custom text", KeyEvent.KEYCODE_ENTER);
你应该这样做。它也隐藏在Android开发者的样例代码“蓝牙聊天”中。用你自己的变量和方法替换“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())。如果这是活动中最后一个或唯一一个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
}
};
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.
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.
这是我的解决方案:
在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;
}
});
我希望这能帮助其他人避免我遇到的问题,因为它们几乎把我逼疯了。
A dependable way to respond to an <enter> in an EditText is with a TextWatcher, a LocalBroadcastManager, and a BroadcastReceiver. You need to add the v4 support library to use the LocalBroadcastManager. I use the tutorial at vogella.com: 7.3 "Local broadcast events with LocalBroadcastManager" because of its complete concise code Example. In onTextChanged before is the index of the end of the change before the change>;minus start. When in the TextWatcher the UI thread is busy updating editText's editable, so we send an Intent to wake up the BroadcastReceiver when the UI thread is done updating editText.
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必须是文本,以便CommonsWare所说的工作。刚刚尝试了所有这些,在试验之前没有inputType,没有任何工作,进入一直注册为软进入。在inputType = text之后,包括setImeLabel在内的所有东西都工作了。
示例:android:inputType="text"
这在LG安卓手机上运行良好。它防止ENTER和其他特殊字符被解释为普通字符。“下一步”或“完成”按钮自动出现,“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;
下面是一个简单的静态函数,您可以将它扔到Utils或keyboard类中,当用户敲击硬件或软件键盘上的返回键时,它将执行代码。这是@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" />
结果(横屏显示):
这将在用户按下返回键时为您提供一个可调用的函数。
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上测试了它。它在小米中也起作用。 我他妈的♥机器人:)
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创建了一个辅助类
使用
new InputPopupBuilder(context)
.setInput(R.string.send,
R.string.enter_your_message,
text -> sendFeedback(text, activity))
.setTitle(R.string.contact_us)
.show();
Code
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'
如果使用DataBinding,请参见https://stackoverflow.com/a/52902266/2914140和https://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()}" />