Android 我如何处理 ImeOptions 的完成按钮点击?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2004344/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:10:27  来源:igfitidea点击:

How do I handle ImeOptions' done button click?

androidandroid-edittextime

提问by d-man

I am having an EditTextwhere I am setting the following property so that I can display the done button on the keyboard when user click on the EditText.

我正在EditText设置以下属性,以便在用户单击 EditText 时可以在键盘上显示完成按钮。

editText.setImeOptions(EditorInfo.IME_ACTION_DONE);

When user clicks the done button on the screen keyboard (finished typing) I want to change a RadioButtonstate.

当用户单击屏幕键盘上的完成按钮(完成输入)时,我想更改RadioButton状态。

How can I track done button when it is hit from screen keyboard?

从屏幕键盘点击完成按钮时如何跟踪完成按钮?

Screenshot showing the bottom right 'done' button on the software keyboard

Screenshot showing the bottom right 'done' button on the software keyboard

回答by Thomas Ahle

I ended up with a combination of Roberts and chirags answers:

我最终得到了 Roberts 和 chirags 的组合答案:

((EditText)findViewById(R.id.search_field)).setOnEditorActionListener(
        new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        // Identifier of the action. This will be either the identifier you supplied,
        // or EditorInfo.IME_NULL if being called due to the enter key being pressed.
        if (actionId == EditorInfo.IME_ACTION_SEARCH
                || actionId == EditorInfo.IME_ACTION_DONE
                || event.getAction() == KeyEvent.ACTION_DOWN
                && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
            onSearchAction(v);
            return true;
        }
        // Return true if you have consumed the action, else false.
        return false;
    }
});

Update:The above code would some times activate the callback twice. Instead I've opted for the following code, which I got from the Google chat clients:

更新:上面的代码有时会激活回调两次。相反,我选择了以下代码,这些代码是从 Google 聊天客户端获得的:

public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    // If triggered by an enter key, this is the event; otherwise, this is null.
    if (event != null) {
        // if shift key is down, then we want to insert the '\n' char in the TextView;
        // otherwise, the default action is to send the message.
        if (!event.isShiftPressed()) {
            if (isPreparedForSending()) {
                confirmSendMessageIfNeeded();
            }
            return true;
        }
        return false;
    }

    if (isPreparedForSending()) {
        confirmSendMessageIfNeeded();
    }
    return true;
}

回答by chikka.anddev

Try this, it should work for what you need:

试试这个,它应该适合你的需要:



editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_DONE) {
       //do here your stuff f
       return true;
    }
    return false;
    } 
});

回答by Vinoj Vetha

<EditText android:imeOptions="actionDone"
          android:inputType="text"/>

The Java code is:

Java代码是:

edittext.setOnEditorActionListener(new OnEditorActionListener() { 
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            Log.i(TAG,"Here you can write the code");
            return true;
        }    
        return false;
    }
});

回答by iRuth

I know this question is old, but I want to point out what worked for me.

我知道这个问题很老,但我想指出什么对我有用。

I tried using the sample code from the Android Developers website(shown below), but it didn't work. So I checked the EditorInfo class, and I realized that the IME_ACTION_SEND integer value was specified as 0x00000004.

我尝试使用Android Developers 网站上的示例代码(如下所示),但没有奏效。所以我检查了 EditorInfo 类,我意识到 IME_ACTION_SEND 整数值被指定为0x00000004.

Sample code from Android Developers:

来自 Android 开发者的示例代码:

editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextEmail
        .setOnEditorActionListener(new OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId,
                    KeyEvent event) {
                boolean handled = false;
                if (actionId == EditorInfo.IME_ACTION_SEND) {
                    /* handle action here */
                    handled = true;
                }
                return handled;
            }
        });

So, I added the integer value to my res/values/integers.xmlfile.

所以,我将整数值添加到我的res/values/integers.xml文件中。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <integer name="send">0x00000004</integer>
</resources>

Then, I edited my layout file res/layouts/activity_home.xmlas follows

然后,我编辑了我的布局文件res/layouts/activity_home.xml如下

<EditText android:id="@+id/editTextEmail"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:imeActionId="@integer/send"
  android:imeActionLabel="@+string/send_label"
  android:imeOptions="actionSend"
  android:inputType="textEmailAddress"/>

And then, the sample code worked.

然后,示例代码起作用了。

回答by Robert Hawkey

More details on how to set the OnKeyListener, and have it listen for the Done button.

有关如何设置 OnKeyListener 并让它侦听 Done 按钮的更多详细信息。

First add OnKeyListener to the implements section of your class. Then add the function defined in the OnKeyListener interface:

首先将 OnKeyListener 添加到类的实现部分。然后添加 OnKeyListener 接口中定义的函数:

/*
 * Respond to soft keyboard events, look for the DONE press on the password field.
 */
public boolean onKey(View v, int keyCode, KeyEvent event)
{
    if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
        (keyCode == KeyEvent.KEYCODE_ENTER))
    {
        // Done pressed!  Do something here.
    }
    // Returning false allows other listeners to react to the press.
    return false;
}

Given an EditText object:

给定一个 EditText 对象:

EditText textField = (EditText)findViewById(R.id.MyEditText);
textField.setOnKeyListener(this);

回答by Donato

While most people have answered the question directly, I wanted to elaborate more on the concept behind it. First, I was drawn to the attention of IME when I created a default Login Activity. It generated some code for me which included the following:

虽然大多数人都直接回答了这个问题,但我想更详细地说明它背后的概念。首先,当我创建一个默认的登录活动时,我注意到了 IME。它为我生成了一些代码,其中包括以下内容:

<EditText
  android:id="@+id/password"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:hint="@string/prompt_password"
  android:imeActionId="@+id/login"
  android:imeActionLabel="@string/action_sign_in_short"
  android:imeOptions="actionUnspecified"
  android:inputType="textPassword"
  android:maxLines="1"
  android:singleLine="true"/>

You should already be familiar with the inputType attribute. This just informs Android the type of text expected such as an email address, password or phone number. The full list of possible values can be found here.

您应该已经熟悉 inputType 属性。这只是通知 Android 预期的文本类型,例如电子邮件地址、密码或电话号码。可以在此处找到可能值的完整列表。

It was, however, the attribute imeOptions="actionUnspecified"that I didn't understand its purpose. Android allows you to interact with the keyboard that pops up from bottom of screen when text is selected using the InputMethodManager. On the bottom corner of the keyboard, there is a button, typically it says "Next" or "Done", depending on the current text field. Android allows you to customize this using android:imeOptions. You can specify a "Send" button or "Next" button. The full list can be found here.

然而,这imeOptions="actionUnspecified"是我不理解其目的的属性。Android 允许您与使用InputMethodManager. 在键盘的底角,有一个按钮,通常显示“下一步”或“完成”,具体取决于当前文本字段。Android 允许您使用android:imeOptions. 您可以指定“发送”按钮或“下一步”按钮。完整列表可以在这里找到。

With that, you can then listen for presses on the action button by defining a TextView.OnEditorActionListenerfor the EditTextelement. As in your example:

这样,您就可以通过TextView.OnEditorActionListenerEditText元素定义 a来监听操作按钮上的按下情况。如您的示例所示:

editText.setOnEditorActionListener(new EditText.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(EditText v, int actionId, KeyEvent event) {
    if (actionId == EditorInfo.IME_ACTION_DONE) {
       //do here your stuff f
       return true;
    }
    return false;
    } 
});

Now in my example I had android:imeOptions="actionUnspecified"attribute. This is useful when you want to try to login a user when they press the enter key. In your Activity, you can detect this tag and then attempt the login:

现在在我的例子中我有android:imeOptions="actionUnspecified"属性。当您想在用户按下 Enter 键时尝试登录时,这很有用。在您的 Activity 中,您可以检测到此标签,然后尝试登录:

    mPasswordView = (EditText) findViewById(R.id.password);
    mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
            if (id == R.id.login || id == EditorInfo.IME_NULL) {
                attemptLogin();
                return true;
            }
            return false;
        }
    });

回答by CoolMind

Thanks to chikka.anddevand Alex Cohnin Kotlin it is:

感谢Kotlin 中的chikka.anddevAlex Cohn,它是:

text.setOnEditorActionListener { v, actionId, event ->
    if (actionId == EditorInfo.IME_ACTION_DONE ||
        event?.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER) {
        doSomething()
        true
    } else {
        false
    }
}

Here I check for Enterkey, because it returns EditorInfo.IME_NULLinstead of IME_ACTION_DONE.

在这里我检查Enter键,因为它返回EditorInfo.IME_NULL而不是IME_ACTION_DONE.

See also Android imeOptions="actionDone" not working. Add android:singleLine="true"in the EditText.

另请参阅Android imeOptions="actionDone" not working。添加android:singleLine="true"EditText

回答by Gibolt

Kotlin Solution

科特林解决方案

The base way to handle it in Kotlin is:

在 Kotlin 中处理它的基本方法是:

edittext.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_DONE) {
        callback.invoke()
        true
    }
    false
}

Kotlin Extension

Kotlin 扩展

Use this to just call edittext.onDone{/*action*/}in your main code. Makes your code far more readable and maintainable

使用它来调用edittext.onDone{/*action*/}你的主代码。使您的代码更具可读性和可维护性

fun EditText.onDone(callback: () -> Unit) {
    setOnEditorActionListener { _, actionId, _ ->
        if (actionId == EditorInfo.IME_ACTION_DONE) {
            callback.invoke()
            true
        }
        false
    }
}

Don't forget to add these options to your edittext

不要忘记将这些选项添加到您的编辑文本中

<EditText ...
    android:imeOptions="actionDone"
    android:inputType="text"/>

If you need inputType="textMultiLine"support, read this post

如果您需要inputType="textMultiLine"支持,请阅读这篇文章