How to Handle IME Options on Action Button Click in Android?
We often observe that a keyboard pops up when we try to enter input in editable fields. These inputs are generally accepted by the application for performing specific functions and display desired results. One of the most common editable fields, that we can see in most of the applications in daily use is the SearchBar.
When the keyboard is invoked, you see a button with a magnifier icon at the bottom. This lets the user assume that clicking this button would help them search their query. However, the developers of this application have explicitly set the magnifier icon, which by default could be something else. This can be done by explicitly specifying the type of icon required using the IME Options. To learn about the list of available icons and how to change them, refer to the below article. Invoking Search Button in Keyboard While Typing in EditText in Android. In this article, we will show you how to handle the on-click events on these buttons.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
Step 3: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
So basically, in the function doSomething, you can observe IME_ACTION_DONE in the outer if condition. This is because when we invoked the keyboard by pressing on the EditText, we saw the Done button. This is when no IME Options is set in attributes of the Edit Text in the Layout or is a default condition. But if you set it to search, go, etc, then you may like to refer below to make the application work. Replace with:
- EditorInfo.IME_ACTION_DONE = When no IME options is specified (default)
- EditorInfo.IME_ACTION_SEARCH = When IME options is actionSearch
- EditorInfo.IME_ACTION_GO = When IME options is actionGo
- EditorInfo.IME_ACTION_NEXT = When IME options is actionNext
- EditorInfo.IME_ACTION_PREVIOUS = When IME options is actionPrevious
- EditorInfo.IME_ACTION_SEND = When IME options is actionSend
Click on EditText and type something. Now press the Done button at the bottom and observe if a Toast appears. Similarly, type in “geeksforgeeks” and observe the Toast.
You can see that we observe different Toasts for different inputs. This shows that our function correctly responds to the keyboard action button (Done button) in the form of Toasts.
Please Login to comment...