Common Input Controls in Android

Introduction to Input Controls in Android

All the applications have some user interface through which user can communicate with the application. This user interface has some input controls like buttons, text fields, seek bars, check boxes, toggle buttons, etc., and some output controls like labels, list views, and tables, etc. Some output controls can also be used as input controls, for example, the user can give input by selecting any item in the list view. Input controls give information to the application which is processed by the application, and the application provides some output through any output control based on the user input. In this tutorial, you will learn about input controls in Android.

Android provides a wide range of input controls. Adding an input control to your Android Activity i.e. user interface is as easy as adding an XML element to the XML layout of your Android application. Every input control in Android has specific input functionality, and some input events and handlers get user input.

Commonly used Input Controls in Android

When the system requires some input from the user, then these input controls are mostly used.

Buttons

Text Fields

Checkboxes

Radio Buttons

Toggle Buttons

Seek Bars

Buttons

Buttons in Android consist of text as well as an image to clearly explain the functionality of the button. Android button can only have text or an image. It is not compulsory for a button to have both text and image. To create a button in your XML file, <Button> tag is used. An event handler must be there to handle the click i.e. onClick.

Button Handler

When the user clicks on the button, an event should fire from that button click As the button object receive an on-click event. To define click event handler for the button, you just need to add an onClick attribute to the button element in XML layout. The value for onClick attribute must be the name of the method you want to call in the response of click event. Java file of the activity must implement the method to perform something on button click.

To implement button click event create a method in a Java file, same as the name mentioned in the XML file. Pass an object of Android View as parameters.

1

2

3

publicvoidSomeMethod(Viewv){

// Do something in response to button click

}

Button handler through code

You can also declare the click event through code in the Java file rather than declaring it in your XML layout. So create the instance of Android Button and implement setOnClickListener. Pass View.OnClickListener object as a parameter and implement onClick inside the method, setOnClickListener().

Text Fields

Text fields are used to give text input, when the user is required to enter something in the form of text, like phone number, name, password, etc. Text fields take input in either single line or multiple lines. Touching the text field places the cursor in the text field and automatically displays the keyboard on the screen. In addition to typing, text fields have much more features like cut, copy or paste the text, along with data lookup via auto-completion. To create a text field in your XML file, <EditText> tag is used.

Text Field in Android

Creating and using the text field in Android

1

2

3

4

5

6

<EditText

android:id="@+id/someID"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:hint="@string/some_hint"//specify some hint for the text field

/>

You can also specify the keyboard type in the text field with android:inputType attribute. For example, if you want the user to enter an email address, you can use textEmailAddress.

Input types in Android text field

text

It displays normal text keyboard.

Syntax

1

android:inputType="textEmailAddress"

textEmailAddress

It displays normal text keyboard with the @ character.

Syntax

1

android:inputType="textEmailAddress"

textUri

It displays normal text keyboard with the / character.

Syntax

1

android:inputType="textUri"

number

It displays a basic number keypad.

Syntax

1

android:inputType="number"

phone

It displays a phone‐style keypad.

Syntax

1

android:inputType="phone"

Getting text from Android text field

If you want to use the text of Android text field in your code, create an instance of EditText.

1

EditText usertext=(EditText)findViewById(R.id.UserText);

Store the input in a string to use.

1

Stringtext=usertext.getText().toString();

Setting Text in Android text field

Similarly, you can also add text in Android text field by creating the instance of EditText and add text by setText() method.

Keyboard Behavior in XML

The inputType in Android allows the bitwise combinations so that you can specify the keyboard behavior and the keyboard layout at the same time.

There are certain keyboard behaviors you can add to XML layout in the inputType.

textMultiLine

It is a normal text keyboard that allows the user to input long strings of text that can include line breaks i.e. Carriage returns.

textCapSentences

It is a normal text keyboard that capitalizes the first letter of each new sentence.

textCapWords

It is a normal text keyboard that capitalizes every word. It is commonly used for person names and titles etc.

textAutoCorrect

It is a normal text keyboard that corrects commonly misspelled words.

textPassword

It is a normal text keyboard, but the characters entered turn into the dots.

Set Multiple attributes to inputType

As inputType has a bitwise behavior, so we can set multiple attributes in one input type. i.e. textMultiLine and textCapWords

1

android:inputType="textMultiLine|textCapWords"

Keyboard Actions

Android also allows you to specify an action when the user completes the input. You can specify the action by using IME (Input Method Editor). This can be done by setting the property of android:imeOptions.

Syntax

1

android:imeOptions="actionSend"

If you won’t specify an input action, the system attempts to identify whether there are any focusable android fields. If any focusable field is found following the current field, the system automatically assigns @code actionNext action to the current EditText so that the user can select next to move to the next field. If there is no next focusable field the system automatically assigns actionDone action.

Responding to the keyboard actions

You can also respond to the keyboard actions by adding an action listener to the EditText as in the case of buttons.

Syntax

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

EditText editText=(EditText)findViewById(R.id.txt_special);

editText.setOnEditorActionListener(newOnEditorActionListener(){

@Override

publicbooleanonEditorAction(TextViewv,intactionId,KeyEvent event)

{

booleanhandled=false;

if(actionId==EditorInfo.IME_ACTION_SEND){

sendMessage();

handled=true;

}

returnhandled;

}

});

Auto-complete in Android text fields

If you want to turn on the suggestions to users as they type, there is a subclass of EditText, which is known as AutoCompleteTextView.

How to provide Auto Complete

If you want to provide auto-complete, you should specify an Adapter that can act as a bridge between view and underlying data of the view to show text suggestions. Adapter also provides access to the data items. And the adapter is also responsible for separate views for each item in the data set having suggestions. Adapters are also used as a bridge between the database and the application, which we will discuss in the coming tutorials.

Check Boxes

Check boxes are used to facilitate the user if the user wants to select one or more options from a list of options available. Typically this list is displayed vertically. As the user can select multiple check boxes so, each check box must have separate action listener.

Checkbox in Android

Create a check box

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<CheckBox

android:id="@+id/checkbox_meat"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/meat"

android:onClick="onCheckboxClicked"

/>

<CheckBox

android:id="@+id/checkbox_cheese"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/cheese"

android:onClick="onCheckboxClicked"

/>

Check Box Handler

When the user checks a checkbox, an onClick event is sent to checkbox object. The value of onClick must be the name of the method which is to be called on the click event as in the case of buttons. The Activity class must implement the corresponding method the get the fired click event, and the method should be public with return type void and get View object as parameters.

Responding to the click event

To check if the checkbox is selected or not, the checked keyword is used.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

publicvoidonCheckboxClicked(View view){

booleanchecked=((CheckBox)view).isChecked();

switch(view.getId()){

caseR.id.checkbox_meat:

if(checked)

//some action

else

//some action

break;

caseR.id.checkbox_cheese:

if(checked)

//some action

else

//some action

break;

}

}

Radio Buttons

Radio buttons allow the user to select one option from the list of options, Check boxes are used if the user should see all the options side by side and choose one from them. RadioButton tag is used to add radio button through XML layout. As radio buttons work together so, they are placed inside RadioGroup tag.

Radio Button in Android

As grouping radio buttons ensures the system that only one radio button is selected at a time.

Syntax

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

<RadioGroup

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:orientation="vertical">

<RadioButton

android:id="@+id/radio_pirates"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/pirates"

android:onClick="onRadioButtonClicked"

/>

<RadioButton

android:id="@+id/radio_ninjas"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="@string/ninjas"

android:onClick="onRadioButtonClicked"

/>

</RadioGroup>

Responding to click events in radio buttons

To check if the radio button is selected or not, the checked keyword is used.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

publicvoidonRadioButtonClicked(View view){

booleanchecked=((RadioButton)view).isChecked();

switch(view.getId()){

caseR.id.radio_pirates:

if(checked)

// Pirates are the best

break;

caseR.id.radio_ninjas:

if(checked)

// Ninjas rule

break;

}

}

Accessing a radio button in code

To access the radio button, you should create an instance of RadioButton in your code and access the radio button through unique the id in the resource file R.java.

1

2

3

4

5

6

7

8

RadioButton rb1=(RadioButton)findViewById(R.id.radio_pirates);

if(rb1.isChecked()){

//do something

}

RadioButton rb1=(RadioButton)findViewById(R.id.radio_ninjas);

if(rb2.isChecked()){

//do something

}

Toggle Buttons

A toggle button allows only two states, either yes or no, on or off.

Toggle Button in Android

Android 4.0 introduces another sliding switch toggle button which is used through Switch object.

Switch in Android

ToggleButtons and Switch controls are the subclasses of CompoundButton.

Creating a toggle button

Similar to other tags toggle buttons are also created by specific ToggleButton tag. To access it in the code, you should specify an Id and a click event to handles the state and actions on state change.

1

2

3

4

5

6

7

8

<ToggleButton

android:id="@+id/togglebutton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textOn="Vibrate on"

android:textOff="Vibrate off"

android:onClick="onToggleClick"

/>

Toggle buttons click handler

On the state change of toggle button, we enabled and disabled vibrate.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

publicvoidonToggleClick(View view){

// Is the toggle on?

booleanon=((ToggleButton)view).isChecked();

if(on)

{

// Enable vibrate

}

else

{

// Disable vibrate

}

}

You can also implement the change listener by creating an instance of ToggleButton and implement setOnCheckedChangeListener method. Pass an object of CompoundButton in parameters.