Как я могу обработать нажатие кнопки ImeOptions?
У меня есть EditText
, где я устанавливаю следующее свойство, чтобы я мог отображать кнопку "Готово" на клавиатуре, когда пользователь нажимает на EditText.
editText.setImeOptions(EditorInfo.IME_ACTION_DONE);
Когда пользователь нажимает кнопку "Готово" на экранной клавиатуре (ввод закончен), я хочу изменить состояние RadioButton
.
Как отследить готовую кнопку, когда она нажата с экранной клавиатуры?
![Screenshot showing the bottom right 'done' button on the software keyboard]()
Ответы
Ответ 1
В итоге у меня появилась комбинация ответов Робертса и Чирага:
((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:
Вышеприведенный код несколько раз активирует обратный вызов дважды. Вместо этого я выбрал следующий код, который я получил от клиентов чата 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;
}
Ответ 2
Попробуйте, это должно работать для того, что вам нужно:
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;
}
});
Ответ 3
<EditText android:imeOptions="actionDone"
android:inputType="text"/>
тогда код 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;
}
});
Ответ 4
Я знаю, что этот вопрос старый, но я хочу указать, что сработало для меня.
Я попытался использовать образец кода с веб-сайта Android Developers (показано ниже), но это не сработало. Поэтому я проверил класс EditorInfo, и я понял, что целочисленное значение IME_ACTION_SEND указано как 0x00000004
.
Пример кода от разработчиков 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;
}
});
Итак, я добавил целочисленное значение в мой файл res/values/integers.xml
.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<integer name="send">0x00000004</integer>
</resources>
Затем я редактировал файл макета 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"/>
И тогда сработал пример кода.
Ответ 5
В то время как большинство людей ответили на вопрос напрямую, я хотел подробнее остановиться на концепции, стоящей за ней. Во-первых, меня привлекло внимание 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"/>
Вы уже должны быть знакомы с атрибутом inputType. Это просто сообщает Android тип ожидаемого текста, например адрес электронной почты, пароль или номер телефона. Полный список возможных значений можно найти здесь.
Это был, однако, атрибут imeOptions="actionUnspecified"
, что я не понял его цели. Android позволяет вам взаимодействовать с клавиатурой, которая появляется снизу экрана, когда текст выбран с помощью InputMethodManager
. В нижнем углу клавиатуры есть кнопка, обычно она говорит "Далее" или "Готово", в зависимости от текущего текстового поля. Android позволяет настроить его с помощью android:imeOptions
. Вы можете указать кнопку "Отправить" или "Далее". Полный список можно найти здесь.
С помощью этого вы можете прослушивать нажатия кнопки действия, определяя TextView.OnEditorActionListener
для элемента EditText
. Как в вашем примере:
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;
}
});
Теперь в моем примере у меня был атрибут android:imeOptions="actionUnspecified"
. Это полезно, когда вы хотите попробовать войти в систему, когда нажимаете клавишу ввода. В своей деятельности вы можете обнаружить этот тег, а затем попытаться войти в систему:
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;
}
});
Ответ 6
Подробнее о том, как установить OnKeyListener, и заставить его прослушивать кнопку "Готово".
Сначала добавьте 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;
}
Для объекта EditText:
EditText textField = (EditText)findViewById(R.id.MyEditText);
textField.setOnKeyListener(this);
Ответ 7
Благодаря chikka.anddev и Алексу Кону в Котлине, это:
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
}
}
Здесь я проверяю ключ Enter
, потому что он возвращает EditorInfo.IME_NULL
вместо IME_ACTION_DONE
.