Click here to Skip to main content
13,148,510 members (67,423 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

7.7K views
156 downloads
6 bookmarked
Posted 4 Sep 2016

Android Smart Keyboard

, 4 Sep 2016
Rate this:
Please Sign up or sign in to vote.
Learn turn the soft keyboard into a smart keyboard that is more responsive and more productive to its users in Android apps.

Introduction

The Android system supports keyboard input for text field either through an on-screen soft keyboard or a hardware keyboard. It is important that your app is optimized to take care of both scenarios so as to enhance user experience (UX).

Every text field expects a certain type of text input depending on its purpose, for example,  email, phone number, or plain text. It will be a great UX if your app can auto display the type of soft keyboard combination that best matched the intended purpose of that text field whenever that text field is on focused. In addition, you app should provide input assistance to the users through such functionalities like spelling suggestions and auto capitalization of the first letter of every new sentence. Yes, the “EditText” widget of Android has these capabilities but you have to know how to configure it to make them work. Let’s find it out…

Specifying Keyboard Type

Create an Android project, a new activity called “KeyboardActivity” with its layout file “activity_keyboard.xml” that renders one “EditText” control. The  content of the “activity_keyboard.xml” is shown below:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="16dp"

    android:paddingLeft="16dp"

    android:paddingRight="16dp"

    android:paddingTop="16dp"

    tools:context="com.peterleowblog.androidux.KeyboardActivity">

    <EditText

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:id="@+id/editText"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="62dp"

        android:hint="Text Field" />
</RelativeLayout>

Launch the app on an AVD,  clicking inside the “EditText” text field will activate the soft keyboard for plain text as shown in Figure 1.

Figure 1: Soft Keyboard for Plain Text
Figure 1: Soft Keyboard for Plain Text

As you can see in Figure 1, plain text is the default input type for  “EditText” control. Let’s explore other input types.

In the “activity_keyboard.xml”, add the ‘android:inputType=”textEmailAddress”‘ attribute to the “<EditText>” node as shown:

android:inputType="textEmailAddress"

Re-launch your app, navigate to the “KeyboardActivity” page, and then click on the “EditText” text field again. You will see a slightly different soft keyboard with a “@” key as shown in Figure 2. Apparently, this “@” key is there to facilitate the input of an email address.

Figure 2: Soft Keyboard for Email Input Type
Figure 2: Soft Keyboard for Email Input Type

In the “activity_keyboard.xml”, change the value of the “android:inputType” attribute of the “<EditText>” node to “number”  as shown:

android:inputType="number"

Re-launch your app, navigate to the “KeyboardActivity” page, and then click on the “EditText” text field again. You will see a soft number pad as shown in Figure 3.

Figure 3: Soft Keyboard for Number Input Type
Figure 3: Soft Keyboard for Number Input Type

Back to Basics

You have just discovered that the “android:inputType” attribute of the “EditText” control can be used to indicate the expected type of text to be entered to the Android system which then provides the best matching soft keyboard for use. Some of the more common input type values for this type of purpose are:

  • text which is the default and calls for a normal text keyboard.
  • textEmailAddress which calls for normal text keyboard that includes the “@” key.
  • number which calls for a basic number keypad.
  • phone which calls for a phone dial pad.

In addition, the “android:inputType” attribute can also define other keyboard behaviors, such as to suggest a list of words while you type, mask password text, allow multi-line input, or to capitalize a new sentence, and many more. Some of these input types are:

  • textPassword” which calls for normal text keyboard, but mask the text entered.
  • textMultiLine” which calls for normal text keyboard that allows users to enter long strings of text that include line breaks.
  • textCapSentences” which calls for normal text keyboard that capitalizes the first alphabet of each new sentence.
  • textAutoCorrect” which calls for normal text keyboard that provides helping words to correct common spelling errors.

You can specify multiple input types to the “android:inputType” attribute of an “EditText” control using the | separator. Change the “android:inputType” attribute of the “EditText” in the “activity_keyboard.xml” as shown below and re-launch it on the AVD.

android:inputType="textMultiLine|textCapSentences"

You will be presented with a plain text soft keyboard. It will auto-capitalize every new sentence as you type and move to a new line when the “carriage return” is pressed as shown in Figure 4.

Figure 4: Text Field with Multi-line and Auto-Capitalization
Figure 4: Text Field with Multi-line and Auto-Capitalization

Homework

You should try out the various input types by modifying the code and watch the outcome on an AVD.

Specifying Keyboard Action Button

You may have noticed that the soft keyboard always provides an action button on the bottom right corner that is appropriate for the current text field. By default, this button performs either a “Next” or “Done” action for single line text fields or acts as a “carriage return” for multi-line text fields. You can, however, choose to assign different action to it to suit your need. This is done by changing the value to the android:imeOptions attribute of the“EditText” control. However, for this to work you must also include the “android:inputType” attribute. Note that this will not work for multi-line input type which only takes a “carriage return” as its action button. Let’s try out an example…

In the “activity_keyboard.xml”, add a new attribute called “android:imeOptions” with a value of “actionSend” together with ‘android:inputType=”text”‘ to the “<EditText>” node as shown:

android:inputType="text"
android:imeOptions="actionSend"

Launch this page on an AVD, notice that the action button is being rendered as a send icon as shown in Figure 5.

Figure 5: Send Action Button
Figure 5: Send Action Button

Homework

Besides “actionSend”, there are other android:imeOptions values, such as “actionGo”, “actionSearch”, “actionPrevious”, “actionNext” and many more, that you can choose from to customize your keyboard action button. Visit android:imeOptions for a complete list of the values and try them out in your code and watch the outcome on an AVD.

Responding to Keyboard Action Button

To perform an action upon pressing a keyboard action button, you will register a  TextView.OnEditorActionListener instance to the “EditText” control and implement its “onEditorAction()” method to respond to the action button identified by its “actionId” defined in the EditorInfo class, such as “IME_ACTION_SEARCH” for the “actionSearch” in “android:imeOptions“. Let’s try out an example:

In the “activity_keyboard.xml”, assign the value “actionSearch” to the “android:imeOptions” of the “<EditText>” node as shown:

android:imeOptions="actionSearch"

Import the necessary packages to the “KeyboardActivity.java” as shown:

import android.view.KeyEvent;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

Lastly, add the following code to the “onCreate()” method of the “KeyboardActivity.java” to respond to keyboard action button.

final EditText editText = (EditText) findViewById(R.id.editText);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        boolean handled = false;
        if (actionId == EditorInfo.IME_ACTION_SEARCH) {
            Toast.makeText(getApplicationContext(), "Searching for " + editText.getText(), Toast.LENGTH_SHORT).show();
            handled = true;
        }
        return handled;
    }
});

Launch this page on an AVD. Clicking on the “EditText” field brings out the soft keyboard with the keyboard action button being rendered as a send icon. Pressing this button will trigger the “onEditorAction()” method which simply echoes a message as shown in Figure 6.

Figure 6: Responding to Keyboard Action Button
Figure 6: Responding to Keyboard Action Button

Homework

Try to modify the  “onEditorAction()” method to work on different keyboard action button and watch the outcome on an AVD.

Any Other Matters

Normally, the soft keyboard will only appear when the text field receives focus, i.e. when you click on it. What if you want the soft keyboard to appear automatically when the activity is loaded? For that, you have to add an attribute called ‘android:windowSoftInputMode=”stateVisible”‘ to the activity in the project’s “AndroidManifest.xml” file. For example,

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.peterleowblog.androidux" >

    <application ...>

        <activity

            <!-- other activitiy -->
        </activity>

        <activity android:name=".KeyboardActivity"

            android:windowSoftInputMode="stateVisible">
            <!-- ... -->
        </activity>

    </application>
    <!-- other declarations -->
</manifest>

From now on, whenever the “KeyboardActivity” page is loaded, the soft keyboard will appear automatically. However, this may result in a problem. Let see…

Add the following code to the “activity_keyboard.xml” to add one “Button” control near the bottom of the screen:

    <!-- ..... -->
    <Button

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="New Button"

        android:id="@+id/button"

        android:layout_alignParentBottom="true"

        android:layout_centerHorizontal="true"

        android:layout_marginBottom="85dp" />
</RelativeLayout>

You expect to see the screen as shown in Figure 7:

Figure 7: A Button Control Added
Figure 7: A Button Control Added

No, you don’t. That is because the button is being hidden behind the auto-appearing soft keyboard whenever the page is loaded. You may wish to move the button above the soft keyboard whenever the soft keyboard appears. Can it be done?

Yes, you can have the cake and eat it too! Just add “adjustResize” to the “android:windowSoftInputMode” like this,

android:windowSoftInputMode="stateVisible|adjustResize"

Seeing is believing. (Figure 8)

Figure 8: Re-positioning of Button on Keyboard Launch
Figure 8: Re-positioning of Button on Keyboard Launch

You wish has come true. You may refer to android:windowSoftInputMode for more options.

Summary

To overcome the constraint of screen size on any Android device, we will have to present the users with the type of keyboard that is most appropriate to the type of input that they are expected to enter. Additional help like auto correct will be greatly appreciated by the users. Incorporating smart keyboard into your app is the sure way to improve productivity and efficiency on keyboarding on small screen devices.

The post Android Smart Keyboard appeared first on Peter Leow's Code Blog.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Peter Leow
Instructor / Trainer
Singapore Singapore
Stop by my website at https://peterleowblog.com/

Check out my publications at https://www.amazon.com/author/peterleow

Follow me on twitter at https://twitter.com/peterleowblog

“Live as if you were to die tomorrow. Learn as if you were to live forever.”
― Mahatma Gandhi

子曰:"三人行,必有我师焉;择其善者而从之,其不善者而改之."

You may also be interested in...

Comments and Discussions

 
GeneralMy vote of 5 Pin
docNyie9-Sep-16 4:05
memberdocNyie9-Sep-16 4:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.170924.2 | Last Updated 4 Sep 2016
Article Copyright 2016 by Peter Leow
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid