Android compose keyboard actions

EditText in Android using Jetpack Compose

EditText is one of the most important widget which is seen in most of the apps. This widget is generally use to get the data from users. Users can directly communicate with the app using this widget. This widget is used to get the data from user in the form of numbers, text or any other text. In this article we will take a look at the implementation of the EditText widget in Android using Jetpack Compose.

Attributes of EditText Widget

Description

value value is use to get the entered value from the user in the text field. placeholder

if the text field is empty we are displaying a hint to the user what he

has to enter in the text field.

keyboardOptions

keyboardOptions is used to add capitalization in the data which is entered by

user in text field, we can also specify auto correction option in this. We can specify

the type of keyboard which we have to display such as (phone, text) and to display

actions which can be performed from the keyboard itself.

textStyle to add styling to the text entered by user. It is used to add font family, font size and styling to our text. maxLines to add maximum lines for our text input field. activeColor

active color is use to when user has click on edit text or the text field is focused and

entering some data in the text field.

singleLine In this we have to specify a boolean value to avoid moving user input into multiple lines. inactiveColor Inactive color is specified when user is not being focused on our Text Input Field. backgroundColor to specify background color for our text input field. leadingIcon

This method is use to add leading icon to our text input field. With this method

we can also specify color(tint) for our icon.

trailingIcon

This method is use to add trailing icon to our text input field. With this method

we can also specify color(tint) for our icon.

Step by Step Implementation

Step 1: Create a New Project

To create a new project in the Android Studio Canary Version please refer to How to Create a new Project in Android Studio Canary Version with Jetpack Compose.

Источник

How to Customize Android Keyboard Actions and Other Hacks

Most of the form-based applications often need to customize the default behavior of the Android soft keyboard. Often it is required to control the type of keyboard you want to present the user for data input, or customize the appearance of keyboard “Enter” key action.

Over the course of this tutorial, we will explain the various code hacks used to control the appearance and behavior of Android soft keyboard. This tutorial covers the following topics:

Let us first began with controlling the type keyboard to display while editing the form data.

Set TextView input type

There are different types of keyboard designed for user convenience. For example, if for entering a number you must display the numerical keyboard. This can be controlled by InputType property of TextView . The InputType controls aspects such as the type of data allowed to enter in a text field. Generally, you can select a single value, though some can be combined together as indicated.

It is important to note that, setting InputType property attribute to anything besides none implies that the text is editable.

Some of the most used input type constants includes, none , text , textCapCharacters , textCapWords , textCapSentences , textAutoCorrect , textAutoComplete , textMultiLine , textImeMultiLine , textUri , textEmailAddress , textPassword , textWebEditText , textPhonetic , textWebEmailAddress , number , phone , datetime , date , and time .

You can set the inputType property in the layout declaration as follows:

Hide the soft keyboard

The following code snippet will help you to hide or dismiss the soft keyboard from the screen and take the input focus out form the editable view.

The hideSoftInputFromWindow() takes an IBinder window token as a parameter. This can be retrieved from any View object currently attached to the window via View.getWindowToken() .

Customize the input method

Now that we understand the different keyboard types based on the TextView inputType property let us customize the appearance of keyboard “Enter” action.

When the keyboard is visible on screen, the text on the Enter key typically indicates its action based on the order of focusable items in the view. While unspecified, the keyboard by default display a “Next” action if there are more focusable views to move to, otherwise it shows “Done” action if the last item is currently focused on. In the case of a multiline field, this action is a line return.

Читайте также:  Включить разнесение антенн bluetooth android

This can be customized using android:imeOptions value in the TextView XML declaration. The android:imeOptions attribute access the following possible values:

  • actionUnspecified: This property displays action of the device’s choice Action event is IME_NULL. This is the default keyboard action.
  • actionGo: This displays Go as the Enter key. Action event is IME_ACTION_GO
  • actionSearch: Displays a search icon as the Enter key Action event is IME_ACTION_SEARCH
  • actionSend: Displays Send as the Enter key. Action event is IME_ACTION_SEND
  • actionNext: Displays Next as the Enter key. Action event is IME_ACTION_NEXT
  • actionDone: Displays Done as the Enter key. Action event is IME_ACTION_DONE

All the above set of action event constants are defined in EditorInfo class.

Let us look at the following example layout with two editable text fields. The first EditText will display the search icon for the Enter key, and the second will display Go. The resulting output may vary depending on current keyboard installed on the device.

Note that, the custom editor options apply only to the appearance of soft input methods. Changing this value will not affect the events that get generated when the user presses on a physical hardware keyboard button.

Adding Custom Action

Customizing what happens when the user presses the Enter key can be just as important as adjusting its appearance. For overriding the default behavior we need to attach an OnEditorActionListener to EditText instance.

The following code snippet shows how to create a custom action for EditTexts.

The boolean return value of onEditorAction() tells the system whether you are consuming the event or it should be passed on to the next possible responder if any. It is important for you to return true when you handle the event yourself, so no other processing occurs. You can return false when you are not handling the event so your application does not steal key events from the rest of the system.
Welcome to EditPad.org – your online plain text editor. Enter or paste your text here. To download and save it, click on the button below.
2

more » Edit Pad – Free Online Text EditorEdit Pad © 2018

Источник

Jetpack compose: Setting ImeAction does not close or change focus for the keyboard

I’m using Jetpack compose 1.0.0-alpha07 . I made a login screen that contains two TextField s customized using other composables.

However, setting ImeAction in keyboardOptions does not seem to work. For instance ImeAction.Next does not move focus to the next TextField. I think I should do something to make it possible, but no document or article has talked even briefly about ImeOptions . Here’s the code I have for the screen:

Login composable:

EmailEdit:

PassEdit:

To perform Done and Next what code should I add?

4 Answers 4

With 1.0.x you can use

  • keyboardOptions : software keyboard options that contains configuration such as KeyboardType and ImeAction
  • keyboardActions when the input service emits an IME action, the corresponding callback is called

use the onImeActionPerformed parameter.

Here’s a working example:

You can use LocalFocusManager.

Inside parent composable of your fields.

To move focus to next field:

Inside onNext of KeyboardActions to move focus in specific direction such as left, right, up and down.

Inside onDone of KeyboardActions to clear focus.

Tried with version 1.0.1

With Compose in this instance you need to create a set of references to each focusable text field on your screen as below (textField1, textField2) and get a reference to the keyboardController.

Then you can add a type of action to your keyboard options signalling how the action button should look when the keyboard is displayed.

In the keyboardActions parameter, you can call a function on the specified IME action — in this case i’ve stated I want textField2 to take focus when the keyboard action button is pressed. You assign the references in the Modifier.focusRequester parameter in the TextField.

Lastly, to make your first TextField take focus when the screen appears, you call a DisposableEffect function where you specify you would like textField1 to take focus when the screen is first displayed.

Источник

Android Keyboard Handling Using Jetpack Compose

Handle keyboard events effectively in your Android apps

In this article, we are going to learn how to manage the Android keyboard in jetpack compose. We’ll be focusing more on IME actions, keyboard types, focus listeners, etc.

Introduction

Jetpack Compose is one of the recent attempts by Google to make it easy for Android developers to build UI.

“Jetpack Compose is a modern toolkit for building native Android UI. Jetpack Compose simplifies and accelerates UI development on Android with less code, powerful tools, and intuitive Kotlin APIs.” — Android Developers

Jetpack Compose is stable version 1.0 is released recently, which means it’s production-ready. So it would be a great time to learn how to work with the next-generation UI kit for Android development.

You will need to install Android Studio — Arctic Fox (2020.3.1) version to use the Jetpack Compose.

Prerequisites

Before going any further, you must have basic knowledge of how to work with Jetpack Compose. If you’re new to Compose, I highly recommend going through the following articles:

Project Setup

Usually, in android, the keyboard appears when there are input fields on the screen.

Читайте также:  Как отправить сообщение по блютузу с андроида

In this compose example, we’ll use OutlinedTextField to explore keyboard actions. We’ll have two input fields. One to indicate name and the other one for amount . We’ll have Scaffold as root and then Column to arrange the OutlinedTextFields vertically. Have a look:

KeyboardOptions

KeyboardOptions is an immutable Kotlin class through which can configure options in the software keyboard. It can be passed as a parameter to TextFields in Jetpack Compose.

KeyboardOptions has mainly four options such as capitalization , autoCorrect , keyboardType , and imeAction . Each has its own unique importance. Let’s see:

  • capitalization : This is used to capitalize the characters of the keyboard based on four types —KeyboardCapitalization.Characters , KeyboardCapitalization.Sentences , KeyboardCapitalization.Words , and KeyboardCapitalization.None .
  • autoCorrect : This is a boolean parameter. If true, it auto-corrects the input based on the user keyboard history, else it won’t correct anything.
  • keyboardType : This is used to show a specific type of keyboard to the user, like an email keyboard with KeyboardType.Email or numeric-only keyboard with KeyboardType.Number , etc.
  • imeAction : This IME action will be honored by the keyboard and show specific icons on the keyboard. For example, if it’s ImeAction.Search then it’ll show a search icon on the keyboard.

KeyboardActions

KeyboardActions is Kotlin class in compose foundation library, it helps developers to execute tasks in response to the user interaction with the IME options in the software keyboard.

Right now, we’ve six keyboard actions available — onDone , onGo , onNext , onPrevious , onSearch , and onSend . The approach of handling keyboard interactions in compose style is way concise than traditional. Have a look:

LocalFocusManager

Now that we’ve finished setting keyboard options and found a way to capture user interaction with the keyboard, it’s time to execute custom actions on the interaction.

One of the most common use-cases is to move the focus of one input field to the next when the user interacted with onNext IME option.

In Jetpack Compose, we’ve got LocalFocusManager to control focus within the composable. First, we need to get the current instance of the focus manager as shown below:

Then we need to use this focusManager inside the onNext KeyboardAction that we implemented in the previous sections to transfer the focus to the next TextField :

We can use this LocalFocusManager to focus on any view not only TextField . We can also transfer the focus in multiple directions — Up , Down , Next , Previous , In , Out , Left , and Right .

KeyboardController

Now as we have two TextFields , for the first field, we use onNext ime option as it has to transfer the focus to the next view, but in the second field we’ll use onDone ime option.

When the user clicked on onDone we need to remove the focus on the TextField and close the keyboard as shown below:

This removes the focus on TextField and closes the keyboard. But there might be a scenario where you need to close the keyboard manually and that’s when we use KeyboardController .

First, we need to get the current instance as shown below:

Then we need to invoke hide function to dismiss the keyboard:

When we bring all the puzzles together, it looks as shown below:

Источник

Клавиатура и аппаратные кнопки

Аппаратные и клавиатурные клавиши

Обработка аппаратных клавиш и клавиатуры имеет следующие методы

  • onKeyDown() — вызывается при нажатии любой аппаратной клавиши;
  • onKeyUp() — вызывается при отпускании любой аппаратной клавиши;

Кроме клавиш, есть ещё другие методы обработки пользовательского ввода (здесь не рассматриваются):

  • onTrackballEvent() — срабатывает при движениях трекбола;
  • onTouchEvent() — обработчик событий сенсорного экрана, срабатывает при касании, убирания пальца и при перетаскивании.

Чтобы ваши компоненты и активности реагировали на нажатия клавиш, переопределите обработчики событий onKeyUp() и onKeyDown():

Параметр keyCode содержит код клавиши, которая была нажата; сравнивайте его со статическими кодами клавиш, хранящимися в классе KeyEvent, чтобы выполнять соответствующую обработку.

Параметр KeyEvent также включает в себя несколько методов: isAltPressed(), isShiftPressed() и isSymPressed(), определяющих, были ли нажаты функциональные клавиши, такие как Alt, Shift или Sym. Статический метод isModifierKey() принимает keyCode и определяет, является ли нажатая клавиша модификатором.

Кнопка Back: Вы уверены, что хотите выйти из программы?

Кнопка Back (Назад) закрывает приложение, точнее текущую активность, но если приложение состоит из одной активности, то это равносильно закрытию всего приложения. В большинстве случаев вам нет никакого дела до неуклюжего пользователя, который по ошибке нажал на кнопку «Back» вместо кнопки Подарить разработчику миллион. Но, если ваша программа, будучи запущенной на телефоне пользователя, потихоньку списывает деньги клиента в счёт Фонда голодных котов, то нужно дать ему шанс задуматься и вывести диалоговое окно с вопросом: «А действительно ли вы хотите выйти из программы?»

Чтобы реализовать такую задачу, нужно переопределить поведение кнопки «Back» через метод активности onBackPressed() следующим образом:

Данный метод появился в Android 2.0. Для более ранних версий использовался стандартный код обработки onKeyDown():

Двойное нажатие на кнопку Back

Другой вариант — выход из приложения при двойном нажатии на кнопку «Back». Удобно в тех случаях, когда считаете, что пользователь может случайно нажать на кнопку, например, во время активной игры. Приложение закроется, если пользователь дважды нажмёт на кнопку в течение двух секунд.

Кнопка Home

Можно отследить нажатие кнопки Home через метод активности onUserLeaveHint():

Обработка кнопки Menu

У телефона, кроме кнопки «Back», есть ещё кнопка «Menu» для вызова команд меню (на старых устройствах). Если необходимо обрабатывать нажатия этой кнопки (например, управление в игре), то используйте следующий код (обычное и долгое нажатие):

Читайте также:  Android on scale and

Должен заметить, что длинное нажатие трудно уловить, так как обычное нажатие постоянно подавляет это событие.

Другие кнопки

Ну на самом деле можно отслеживать не только нажатие кнопки Меню, но и кнопку Поиска и кнопки увеличения громкости.

Обратите внимание, что для кнопки громкости возвращаем false, т.е. мы не переопределяем поведение кнопки, а оставляем её на усмотрение системы.

Пример работы с кнопками громкости можно посмотреть в статье Рингтоны. Управление громкостью

По такому же принципу работает метод onKeyUp(). Метод onKeyLongPress() можно использовать, если в методе onKeyDown() был задействован метод event.startTracking(), отслеживающий поведение кнопки. В нашем примере мы отслеживали кнопку Volume_Up.

Прячем клавиатуру

Бывает так, что при запуске активности сразу выскакивает клавиатура. Если такое поведение не нравится, то пропишите в манифесте нужное значение у атрибута android:windowSoftInputMode (см. ниже).

В некоторых случаях хочется убрать клавиатуру с экрана, не нажимая кнопку «Back», а программно. В одном моём приложении, где было много текстовых полей, я воспользовался следующим кодом при щелчке кнопки:

Код так выглядит, если писать его в Activity. Если расположить его в другом классе, экземпляр Activity нужно передать туда как параметр и вызывать методы как activity.getApplicationContext(), где activity — экземпляр Activity.

Можно избавить компонент от фокуса:

Чтобы принудительно показать клавиатуру, используйте следующий код:

Кстати, повторный вызов метода закроет клавиатуру. Указанный способ не требует наличия элементов View.

Если продолжить тему показа клавиатуры, то может возникнуть следующая ситуация. Допустим у вас есть DialogFragment с EditText. При выводе диалогового окна вам нужно установить фокус на EditText и показать клавиатуру:

Либо используйте тег для нужного EditText.

Изменить вид клавиатуры для EditText

Когда элемент EditText получает фокус, то появляется клавиатура. Можно установить нужный вид клавиатуры через атрибут InputType или программно через метод setInputType():

TYPE_CLASS_DATETIME — дата и время
TYPE_CLASS_NUMBER — цифры
TYPE_CLASS_TEXT — буквы

Переопределяем кнопку Enter

Кроме атрибута InputType можно также использовать атрибут android:imeOptions в компоненте EditText, который позволяет заменить кнопку Enter на клавиатуре на другие кнопки, например, Next, Go, Search и др. Возможны следующие значения:

  • actionUnspecified: Используется по умолчанию. Система сама выбирает нужный вид кнопки (IME_NULL)
  • actionGo: Выводит надпись Go. Действует как клавиша Enter при наборе адреса в адресной строке браузера (IME_ACTION_GO)
  • actionSearch: Выводит значок поиска (IME_ACTION_SEARCH)
  • actionSend: Выводит надпись Send (IME_ACTION_SEND)
  • actionNext: Выводит надпись Next (IME_ACTION_NEXT)
  • actionDone: Выводи надпись Done (IME_ACTION_DONE)

Чтобы увидеть все варианты воочию, можете создать несколько текстовых полей и переключаться между ними:

Чтобы реагировать на нажатия разных состояний кнопки Enter, необходимо реализовать интерфейс TextView.OnEditorActionListener. Небольшой пример:

В нашем примере если пользователь ищет что-то, не связанное с котом, то кнопка поиска не будет выполнять желание владельца устройства.

Также можно поменять текст на кнопке с помощью атрибута android:imeActionLabel:

Текст на кнопке поменялся, но вот обработка Enter из предыдущего примера у меня перестала работать. Мой неработающий код на память.

Upd: Читатель Максим Г. предложил следующее решение проблемы. Убираем атрибуты imeOptions, imeActionId, imeActionLabel и установим их программно.

По желанию можете отслеживать только у нужного поля. Поставьте дополнительное условие после первого блока if:

Интерфейс OnKeyListener

Чтобы среагировать на нажатие клавиши внутри существующего представления из активности, реализуйте интерфейс OnKeyListener и назначьте его для объекта View, используя метод setOnKeyListener(). Вместо того, чтобы реализовывать отдельные методы для событий нажатия и отпускания клавиш, OnKeyListener использует единое событие onKey().

Используйте параметр keyCode для получения клавиши, которая была нажата. Параметр KeyEvent нужен для распознавания типа события (нажатие представлено константой ACTION_DOWN, а отпускание — ACTION_UP).

Сдвигаем активность

Чтобы всплывающая клавиатура не заслоняла элемент интерфейса, который получил фокус, а сдвигала активность вверх, можно в манифесте для нужной активности прописать атрибут android:windowSoftInputMode с параметром adjustPan:

Также доступны и другие параметры:

  • stateUnspecified — настройка по умолчанию. Система сама выбирает подходящее поведение клавиатуры.
  • stateUnchanged — клавиатура сохраняет своё последнее состояние (видимое или невидимое), когда активность с текстовым полем получает фокус.
  • stateHidden — клавиатура скрыта, когда открывается активность. Клавиатура появится при наборе текста. Если пользователь переключится на другую активность, то клавиатура будут скрыта, но при возвращении назад клавиатура останется на экране, если она была видима при закрытии активности.
  • stateAlwaysHidden — клавиатура всегда скрывается, если активность получает фокус.
  • stateVisible — клавиатура видима.
  • stateAlwaysVisible — клавиатура становится видимой, когда пользователь открывает активность.
  • adjustResize — размеры компонентов в окне активности могут изменяться, чтобы освободить место для экранной клавиатуры.
  • adjustPan — окно активности и его компоненты не изменяются, а сдвигаются таким образом, чтобы текстовое поле с фокусом не было закрыто клавиатурой.
  • adjustUnspecified — настройка по умолчанию. Система сама выбирает нужный режим.

Параметры с префиксом state можно комбинировать с настройками с префиксом adjust:

Например, чтобы показать клавиатуру при старте активности, используйте stateVisible.

Данные настройки доступны и программно. Например, код для adjustResize:

Кстати, этот код не сработает в полноэкранном режиме (флаг FLAG_FULLSCREEN). Сверяйтесь с документацией.

Узнать выбранный язык на клавиатуре

Для определения текущего языка на клавиатуре можно использовать следующий код.

Следует быть осторожным с примером. На эмуляторе с Android 6.0 пример работал корректно. На реальных устройствах у меня корректно определялся русский язык, но при переключении на английский язык выдавал пустую строку или значение «zz». В этом случае можно прибегнуть к условиям if и проверять ожидаемое значение.

Источник

Оцените статью