0% found this document useful (0 votes)
26 views120 pages

Chapter 4

Uploaded by

Sayee Lembhe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views120 pages

Chapter 4

Uploaded by

Sayee Lembhe
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Android UI Controls (Textview, EditText,

Radio Button, Checkbox)


In android UI or input controls are the interactive or View components that are used to
design the user interface of an application. In android we have a wide variety of UI or input
controls available, those are TextView, EditText, Buttons, Checkbox, Progressbar, Spinners,
etc.

Following is the pictorial representation of user interface (UI) or input controls in android
application.

Generally, in android the user interface of an app is made with a collection of View and
ViewGroup objects.

The View is a base class for all UI components in android and it is used to create interactive
UI components such as TextView, EditText, Checkbox, Radio Button, etc. and it is
responsible for event handling and drawing.

The ViewGroup is a subclass of View and it will act as a base class for layouts and layout
parameters. The ViewGroup will provide invisible containers to hold other Views or
ViewGroups and to define the layout properties.

To know more about View and ViewGroup in android applications, check this Android View
and ViewGroup.
In android, we can define a UI or input controls in two ways, those are

 Declare UI elements in XML


 Create UI elements at runtime

The android framework will allow us to use either or both of these methods to define our
application’s UI.

Declare UI Elements in XML


In android, we can create layouts same as web pages in HTML by using default Views and
ViewGroups in the XML file. The layout file must contain only one root element, which
must be a View or ViewGroup object. Once we define the root element, then we can add
additional layout objects or widgets as a child elements to build View hierarchy that defines
our layout.

Following is the example of defining UI controls (TextView, EditText, Button) in the XML
file (activity_main.xml) using LinearLayout.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"

android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Name" />
<EditText
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"/>
<Button
android:id="@+id/getName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Name" />
</LinearLayout>
In android, each input control is having a specific set of events and these events will be raised
when the user performs particular action like, entering the text or touches the button.

Note: we need to create a user interface (UI) layout files in /res/layout project directory, then
only the layout files will compile properly.

Load XML Layout File from an Activity


Once we are done with the creation of layout with UI controls, we need to load the XML
layout resource from our activity onCreate() callback method like as shown below.

protected void onCreate(Bundle savedInstanceState) {


super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

If you observe above code we are calling our layout using setContentView method in the
form of R.layout.layout_file_name. Here our xml file name is activity_main.xml so we
used file name activity_main.

Generally, during the launch of our activity, onCreate() callback method will be called by
android framework to get the required layout for an activity.

Create UI Element at Runtime


If we want to create UI elements at runtime, we need to create our own custom View and
ViewGroup objects programmatically with required layouts.

Following is the example of creating UI elements (TextView, EditText, Button) in


LinearLayout using custom View and ViewGroup objects in an activity programmatically.

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView textView1 = new TextView(this);
textView1.setText("Name:");
EditText editText1 = new EditText(this);
editText1.setText("Enter Name");
Button button1 = new Button(this);
button1.setText("Add Name");
LinearLayout linearLayout = new LinearLayout(this);
linearLayout.addView(textView1);
linearLayout.addView(editText1);
linearLayout.addView(button1);
setContentView(linearLayout);
}
}

By creating a custom View and ViewGroups programmatically, we can define UI controls in


layouts based on our requirements in android applications.

Width and Height


When we define a UI controls in a layout using an XML file, we need to set width and height
for every View and ViewGroup elements using layout_width and layout_height attributes.

Following is the example of setting width and height for View and ViewGroup elements in
the XML layout file.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"

android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enter Name" />
</LinearLayout>

If you observe above example, we used different values to set layout_width and
layout_height, those are

 match_parent
 wrap_content

If we set value match_parent, then the View or ViewGroup will try to match with parent
width or height.
If we set value wrap_content, then the View or ViewGroup will try to adjust its width or
height based on the content.

Android Different Types of UI Controls


We have a different type of UI controls available in android to implement the user interface
for our android applications.

Following are the commonly used UI or input controls in android applications.

 TextView
 EditText
 AutoCompleteTextView
 Button
 ImageButton
 ToggleButton
 CheckBox
 RadioButton
 RadioGroup
 ProgressBar
 Spinner
 TimePicker
 DatePicker
 SeekBar
 AlertDialog
 Switch
 RatingBar

Android TextView
In android, TextView is a user interface control that is used to display the text to the user.

To know more about TextView control check this, Android TextView with Examples.

Android EditText
In android, EditText is a user interface control which is used to allow the user to enter or
modify the text.
To know more about EditText, check this Android EditText with Examples.

Android AutoCompleteTextView
In android, AutoCompleteTextView is an editable text view which is used to show the list of
suggestions based on the user typing text. The list of suggestions will be shown as a
dropdown menu from which the user can choose an item to replace the content of the textbox.

To know more about AutoCompleteTextView, check this Android AutoCompleteTextView


with Examples.

Android Button
In android, Button is a user interface control that is used to perform an action when the user
clicks or tap on it.

To know more about Button in android check this, Android Buttons with Examples.

Android Image Button


In android, Image Button is a user interface control that is used to display a button with an
image to perform an action when the user clicks or tap on it.

Generally, the Image button in android looks similar as regular Button and perform the
actions same as regular button but only difference is for image button we will add an image
instead of text.

To know more about Image Button in android check this, Android Image Button with
Examples.

Android Toggle Button


In android, Toggle Button is a user interface control that is used to display ON (Checked) or
OFF (Unchecked) states as a button with a light indicator.

To know more about Toggle Button in android check this, Android Toggle Button with
Examples.

Android CheckBox
In android, Checkbox is a two-states button that can be either checked or unchecked.
To know more about CheckBox in android check this, Android CheckBox with Examples.

Android Radio Button


In android, Radio Button is a two-states button that can be either checked or unchecked and
it cannot be unchecked once it is checked.

To know more about Radio Button in android check this, Android Radio Button with
Examples.

Android Radio Group


In android, Radio Group is used to group one or more radio buttons into separate groups
based on our requirements.

In case if we group radio buttons using the radio group, at a time only one item can be
selected from the group of radio buttons.

To know more about Radio Group in android check this, Android Radio Group with
Examples.

Android ProgressBar
In android, ProgressBar is a user interface control which is used to indicate the progress of
an operation.

To know more about ProgressBar, check this Android ProgressBar with Examples.

Android Spinner
In android, Spinner is a drop-down list which allows a user to select one value from the list.

To know more about Spinner, check this Android Spinner with Examples.

Android TimePicker
In android, TimePicker is a widget for selecting the time of day, either in 24-hour or AM/PM
mode.

To know more about TimePicker, check this, Android TimePicker with Examples.

Android DatePicker
In android, DatePicker is a widget for selecting a date.

To know more about DatePicker, check this Android DatePicker with Examples.

We learn all android user interface (UI) controls in next chapters in detailed manner with
examples.
Android TextView with Examples
In android, TextView is a user interface control that is used to set and display the text to the
user based on our requirements. The TextView control will act as like label control and it
won’t allow users to edit the text.

In android, we can create a TextView control in two ways either in XML layout file or create
it in Activity file programmatically.

Create a TextView in Layout File


Following is the sample way to define TextView control in XML layout file in android
application.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="Welcome to Tutlane"
android:textColor="#86AD33"
android:textSize="20dp"
android:textStyle="bold" />
</LinearLayout>

If you observe above code snippet, here we defined a TextView control in xml layout file to
display the text in android application.

Create a TextView in Activity File


In android, we can create a TextView control programmatically in an activity file based on
our requirements.

Following is the example of creating a TextView control dynamically in an activity file.


public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linearlayout);
TextView textView = new TextView(this);
textView.setText("Welcome to Tutlane");
linearLayout.addView(textView);
}
}

Set the Text of Android TextView


In android, we can set the text of TextView control either while declaring it in Layout file or
by using setText() method in Activity file.

Following is the example to set the text of TextView control while declaring it in the XML
Layout file.

<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to Tutlane" />

If you observe above example we used android:text property to the set required text for
TextView control in XML Layout file.

Following is another way to set the text of textview control programmatically in activity file
using setText() method.

TextView tv = (TextView)findViewById(R.id.textView1);
tv.setText("Welcome to Tutlane");

If you observe above code snippet, we are getting the TextView control which we defined in
XML layout file using id property and setting the text using setText() method.

Android TextView Attributes


The following are some of the commonly used attributes related to TextView control in
android applications.

Attribute Description
android: id It is used to uniquely identify the control
It will automatically found and convert URLs and email
android:autoLink
addresses as clickable links.
android: ems It is used to make the textview be exactly this many ems wide.
android:hint It is used to display the hint text when text is empty
android:width It makes the TextView be exactly this many pixels wide.
android:height It makes the TextView be exactly this many pixels tall.
android:text It is used to display the text.
android:textColor It is used to change the color of the text.
It is used to specify how to align the text by the view's x and y-
android:gravity
axis.
android:maxWidth It is used to make the TextView be at most this many pixels wide.
android:minWidth It is used to make the TextView be at least this many pixels wide.
android:textSize It is used to specify the size of the text.
android:textStyle It is used to change the style (bold, italic, bolditalic) of text.
android:textAllCaps It is used to present the text in all CAPS
It is used to specify the Typeface (normal, sans, serif,
android:typeface
monospace) for the text.
android:textColor It is used to change the color of the text.
android:textColorHighlight It is used to change the color of text selection highlight.
android:textColorLink It is used to change the text color of links.
android:inputType It is used to specify the type of text being placed in text fields.
android:fontFamily It is used to specify the fontFamily for the text.
android:editable If we set, it specifies that this TextView has an input method.

Android TextView Example


Following is the example of using TextView control in the android application.

Create a new android application using android studio and give names as TextViewExample.
In case if you are not aware of creating an app in android studio check this article Android
Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown
below
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="Welcome to Tutlane"
android:textColor="#86AD33"
android:textSize="20dp"
android:textStyle="bold" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="15dp"
android:textAllCaps="true" />
<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to Tutlane"
android:textStyle="bold"
android:textColor="#fff"
android:background="#7F3AB5"
android:layout_marginBottom="15dp"/>
<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:autoLink="email|web"
android:text="For more details visit http://tutlane.com and send mail to
[email protected]" />
</LinearLayout>

Once we are done with creation of layout with required controls, we need to load the XML
layout resource from our activity onCreate() callback method, for that open main activity file
MainActivity.java from \java\com.tutlane.textviewexample path and write the code like as
shown below.
MainActivity.java
package com.tutlane.textviewexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView)findViewById(R.id.textView2);
tv.setText("Welcome to Tutlane");
}
}

If you observe above code we are calling our layout using setContentView method in the
form of R.layout.layout_file_name. Here our xml file name is activity_main.xml so we
used file name activity_main and we are setting text to one of our TextView control
(textView2) in our activity file.

Generally, during the launch of our activity, the onCreate() callback method will be called
by the android framework to get the required layout for an activity.

Output of Android TextView Example


When we run the above example using the android virtual device (AVD) we will get a result
like as shown below.
Android AutoCompleteTextView with
Examples
In android, AutoCompleteTextView is an editable text view which is used to show the list of
suggestions based on the user typing text. The list of suggestions will be shown as a
dropdown menu from which the user can choose an item to replace the content of the textbox.

The AutoCompleteTextView is a subclass of EditText class so we can inherit all the


properties of EditText in AutoCompleteTextView based on our requirements.

Following is the pictorial representation of using AutoCompleteTextView in android


applications.

Generally, the dropdown list of suggestions can be obtained from the data adaptor and those
suggestions will be appeared only after giving the number characters defined in the
Threshold limit.

The Threshold property of AutoCompleteTextView is used to define the minimum number


of characters the user must type to see the list of suggestions.

The dropdown list of suggestions can be closed at any time in case if no item is selected from
the list or by pressing the back or enter key.

In android, we can create an AutoCompleteTextView control in two ways either in the XML
layout file or create it in the Activity file programmatically.
Create AutoCompleteTextView in Layout File
Following is the sample way to define AutoCompleteTextView control in the XML layout
file in the android application.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<AutoCompleteTextView
android:id="@+id/autoComplete_Country"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>

If you observe above code snippet, here we defined AutoCompleteTextView control in xml
layout file.

Create AutoCompleteTextView Control in Activity File


In android, we can create AutoCompleteTextView control programmatically in an activity
file to show the list of suggestions based on the user entered text.

Following is the example of creating AutoCompleteTextView control dynamically in


activity file.

LinearLayout l_layout = (LinearLayout) findViewById(R.id.linear_Layout);


AutoCompleteTextView actv = new AutoCompleteTextView(this);

l_layout.addView(actv);

Set the Text of Android AutoCompleteTextView


In android, we can set the text of AutoCompleteTextView control by using setAdapter()
method in Activity file.

Following is example of binding data AutoCompleteTextView in activity file using


setAdapter() method.
String[] Countries = { "India", "USA", "Australia", "UK", "Italy", "Ireland", "Africa" };

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,


android.R.layout.simple_dropdown_item_1line, Countries);
AutoCompleteTextView actv =
AutoCompleteTextView)findViewById(R.id.autoComplete_Country);
actv.setAdapter(adapter);

If you observe above code snippet, we are finding the AutoCompleteTextView control
which we defined in XML layout file using id property and binding the data using
setAdapter() method.

Android AutoCompleteTextView Attributes


Following are the some of commonly used attributes related to AutoCompleteTextView
control in android applications.

Attribute Description
android:id It is used to uniquely identify the control
It is used to specify how to align the text like left, right, center,
android:gravity
top, etc.
android:text It is used to set the text.
android:hint It is used to display the hint text when text is empty
android:textColor It is used to change the color of the text.
android:textColorHint It is used to change the text color of hint text.
android:textSize It is used to specify the size of text.
android:textStyle It is used to change the style (bold, italic, bolditalic) of text.
It is used to set the background color for autocomplete textview
android:background
control
android:ems It is used to make the textview be exactly this many ems wide.
android:width It makes the TextView be exactly this many pixels wide.
android:height It makes the TextView be exactly this many pixels tall.
android:textColorHighlight It is used to change the color of the text selection highlight.
android:fontFamily It is used to specify the fontFamily for the text.

Android AutoCompleteTextView Control Example


Following is the example of defining AutoCompleteTextView control in LinearLayout to
bind the data to defined control using a data adapter and getting the selected list item value in
the android application.
Create a new android application using android studio and give names as
AutoCompleteTextViewExample. In case if you are not aware of creating an app in android
studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown
below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:orientation="vertical"
android:id="@+id/linear_Layout">
<AutoCompleteTextView
android:id="@+id/ac_Country"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="100dp"
android:hint="Enter Country Name"/>
</LinearLayout>

If you observe above code we created AutoCompleteTextView control in XML Layout file.

Once we are done with the creation of layout with required control, we need to load the XML
layout resource from our activity onCreate() callback method, for that open main activity file
MainActivity.java from \java\com.tutlane.autocompletetextviewexample path and write
the code like as shown below.

MainActivity.java
package com.tutlane.autocompletetextviewexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


String[] Countries = { "India", "USA", "Australia", "UK", "Italy", "Ireland", "Africa" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line, Countries);
AutoCompleteTextView actv =
(AutoCompleteTextView)findViewById(R.id.ac_Country);
actv.setThreshold(1);
actv.setAdapter(adapter);
actv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Selected Item: " +
parent.getSelectedItem(), Toast.LENGTH_SHORT).show();
}
});
}
}

If you observe above code we are calling our layout using setContentView method in the
form of R.layout.layout_file_name in our activity file. Here our xml file name is
activity_main.xml so we used file name activity_main and binding data to our
AutoCompleteTextView using ArrayAdapter and getting selected list item value using
getSelectedItem() method.

Generally, during the launch of our activity, onCreate() callback method will be called by
the android framework to get the required layout for an activity.

Output of Android AutoCompleteTextView Example


When we run above example using the android virtual device (AVD) we will get a result like
as shown below.
This is how we can use AutoCompleteTextView control in android applications to show the
list of suggestions to the user based on the text they entered in the textbox.
Android EditText with Examples
In android, EditText is a user interface control which is used to allow the user to enter or modify
the text. While using EditText control in our android applications, we need to specify the type of
data the text field can accept using the inputType attribute.

For example, if it accept plain text, then we need to specify the inputType as “text”. In case
if EditText field is for password, then we need to specify the inputType as “textPassword”.

In android, EditText control is an extended version of TextView control with additional features
and it is used to allow users to enter input values.

In android, we can create EditText control in two ways either in XML layout file or create it
in Activity file programmatically.

Create a EditText in Layout File


Following is the sample way to define EditText control in XML layout file in android application.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android
"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/txtSub"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Subject"
android:inputType="text"/>
</LinearLayout>
If you observe above code snippet, here we defined EditText control to accept plain text by
using inpuType as “text” in xml layout file.

Create EditText Control in Activity File


In android, we can create EditText control programmatically in an activity file to allow users to
enter text based on our requirements.

Following is the example of creating EditText control dynamically in an activity file.

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.l
inearlayout);
EditText et = new EditText(this);
et.setHint("Subject");
linearLayout.addView(et);
}
}

Set the Text of Android EditText


In android, we can set the text of EditText control either while declaring it in Layout file or by
using setText() method in Activity file.

Following is the example to set the text of TextView control while declaring it in XML Layout file.

<EditText
android:id="@+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Welcome to Tutlane" />
If you observe above example we used android:text property to the set required text
for EditText control in XML Layout file.

Following is another way to set the text of EditText control programmatically in activity file using
setText() method.

EditText et = (EditText)findViewById(R.id.editText1);
et.setText("Welcome to Tutlane");
If you observe above code snippet, we are finding the EditText control which we defined in XML
layout file using id property and setting the text using setText() method.

Get Text of Android EditText


In android, we can get the text of EditText control by using getText() method in Activity file.

Following is the example to get text of EditText control programmatically in activity file
using getText() method.

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText et = (EditText) findViewById(R.id.txtSub);
String name = et.getText().toString();
}
}
If you observe above code snippet, we are finding the EditText control which we defined in XML
layout file using id property and getting the text of EditText control using getText() method.

Android EditText Attributes


The following are some of the commonly used attributes related to EditText control in android
applications.

Attribute Description

android:id It is used to uniquely identify the control

android:gravity It is used to specify how to align the text like left, right, center, top, etc.

android:text It is used to set the text.

android:hint It is used to display the hint text when text is empty

android:textColor It is used to change the color of the text.

android:textColorHint It is used to change the text color of hint text.

android:textSize It is used to specify the size of the text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for edit text control

android:ems It is used to make the textview be exactly this many ems wide.

android:width It makes the TextView be exactly this many pixels wide.

android:height It makes the TextView be exactly this many pixels tall.


Attribute Description

android:maxWidth It is used to make the TextView be at most this many pixels wide.

android:minWidth It is used to make the TextView be at least this many pixels wide.

android:textAllCaps It is used to present the text in all CAPS

android:typeface It is used to specify the Typeface (normal, sans, serif, monospace) for the text

android:textColorHighlight It is used to change the color of text selection highlight.

android:inputType It is used to specify the type of text being placed in text fields.

android:fontFamily It is used to specify the fontFamily for the text.

android:editable If we set false, EditText won't allow us to enter or modify the text

Android EditText Control Example


Following is the example of using multiple EditText controls with different input types like
password, phone, etc. in LinearLayout to build an android application.
Create a new android application using android studio and give names as EditTextExample. In
case if you are not aware of creating an app in android studio check this article Android Hello
World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown
below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android
"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="40dp"
android:orientation="vertical" android:id="@+id/linearlayout" >
<EditText
android:id="@+id/txtName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="25dp"
android:ems="10"
android:hint="Name"
android:inputType="text"
android:selectAllOnFocus="true" />
<EditText
android:id="@+id/txtPwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Password 0 to 9"
android:inputType="numberPassword" />
<EditText
android:id="@+id/txtEmai"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Email"
android:inputType="textEmailAddress" />
<EditText
android:id="@+id/txtDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText3"
android:ems="10"
android:hint="Date"
android:inputType="date" />
<EditText
android:id="@+id/txtPhone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Phone Number"
android:inputType="phone"
android:textColorHint="#FE8DAB"/>
<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="submit"
android:textSize="16sp"
android:textStyle="normal|bold" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/resultView"
android:layout_marginTop="25dp"
android:textSize="15dp"/>
</LinearLayout>
If you observe above code we created multiple EditText controls with different inputTypes, such
as password, email address, date, phone number, plain text.

Once we are done with the creation of layout with required controls, we need to load the XML
layout resource from our activity onCreate() callback method, for that open main activity
file MainActivity.java from \java\com.tutlane.edittextexample path and write the code like as
shown below.

MainActivity.java
package com.tutlane.edittextexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.w3c.dom.Text;

public class MainActivity extends AppCompatActivity {


Button btnSubmit;
EditText name, password, email, dob, phoneno;
TextView result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name=(EditText)findViewById(R.id.txtName);
password = (EditText)findViewById(R.id.txtPwd);
email = (EditText)findViewById(R.id.txtEmai);
dob = (EditText)findViewById(R.id.txtDate);
phoneno= (EditText)findViewById(R.id.txtPhone);
btnSubmit = (Button)findViewById(R.id.btnSend);
result = (TextView)findViewById(R.id.resultView);
btnSubmit.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (name.getText().toString().isEmpty() || password.get
Text().toString().isEmpty() || email.getText().toString().isEmpty() |
| dob.getText().toString().isEmpty()
|| phoneno.getText().toString().isEmpty()) {
result.setText("Please Fill All the Details");
} else {
result.setText("Name - " + name.getText().toString
() + " \n" + "Password - " + password.getText().toString()
+ " \n" + "E-Mail - " + email.getText().to
String() + " \n" + "DOB - " + dob.getText().toString()
+ " \n" + "Contact - " + phoneno.getText()
.toString());
}
}
});
}
}
If you observe above code we are calling our layout using setContentView method in the form
of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so
we used file name activity_main and we are getting the text of our EditText controls whenever
we click on button.

Generally, during the launch of our activity, the onCreate() callback method will be called by the
android framework to get the required layout for an activity.

Output of Android EditText Example


When we run the above example using the android virtual device (AVD) we will get a result like as
shown below.

If you observe the above result, the system displaying an appropriate on-screen keyboard for
each EditText control based on the defined inputType attribute and displayed a message if we
click on the button without entering details in fields.
Once we enter details in all fields and click on Button we will get a result like as shown below.

This is how we can use EditText control in android applications to allow the user to enter or
modify the text based on our requirements.
Android Button with Examples
In android, Button is a user interface control that is used to perform an action whenever the
user clicks or tap on it.

Generally, Buttons in android will contain a text or an icon or both and perform an action
when the user touches it.

Following is the pictorial representation of using Buttons in android applications.

In android, we have a different type of buttons available to use based on our requirements,
those are ImageButton, ToggleButton, RadioButton.

In android, we can create a Button control in two ways either in the XML layout file or create
it in the Activity file programmatically.

Create Button in XML Layout File


Following is the sample way to define Button control in the XML layout file in the android
application.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add" />
</LinearLayout>

If you observe above code snippet, here we defined Button control in xml layout file.
Create Button Control in Activity File
In android, we can create Button control programmatically in an activity file based on our
requirements.

Following is the example of creating Button control dynamically in the activity file.

LinearLayout layout = (LinearLayout)findViewById(R.id.l_layout);


Button btn = new Button(this);
btn.setText("Test");
layout.addView(btn);

Android Handle Button Click Events


Generally, whenever the user clicks on a Button, the Button object will receives an on-click
event.

In android, we can define a button click event in two ways either in the XML layout file or
create it in the Activity file programmatically.

Define Button Click Event in XML Layout File


We can define click event handler for button by adding android:onClick attribute to the
<Button> element in our XML layout file.

The value of android:onClick attribute must be the name of the method which we need to
call in response to a click event and the Activity file which hosting XML layout must
implement the corresponding method.

Following is the example of defining a button click event using android:onClick attribute in
an XML layout file.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:onClick="addOperation"/>
</LinearLayout>

In Activity that hosts our XML layout file, we need to implement click event method like as
shown below

/** Called when the user touches the button */


public void addOperation(View view) {
// Do something in response to the button click
}

Define Button Click Event in Activity File


In android, we can define the button click event programmatically in the Activity file rather
than XML layout file.

To define button click programmatically, create View.OnClickListener object and assign it


to the button by calling setOnClickListener(View.OnClickListener) like as shown below.

Button btnAdd = (Button)findViewById(R.id.addBtn);


btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {

// Do something in response to button click


}
});
}

This is how we can handle button click events in android applications based on our
requirements.

Android Button Control Attributes


Following are the some of commonly used attributes related to Button control in android
applications.
Attribute Description
android:id It is used to uniquely identify the control
It is used to specify how to align the text like left, right, center, top,
android:gravity
etc.
android:text It is used to set the text.
android:textColor It is used to change the color of text.
android:textSize It is used to specify the size of the text.
android:textStyle It is used to change the style (bold, italic, bolditalic) of text.
android:background It is used to set the background color for button control.
android:padding It is used to set the padding from left, right, top and bottom.
android:drawableBottom It’s drawable to be drawn to the below of text.
android:drawableRight It’s drawable to be drawn to the right of text.
android:drawableLeft It’s drawable to be drawn to the left of the text.

Android Button Control Example


Following is the example of defining a one Button and two EditText controls in
LinearLayout to get the data of EditText controls when click on Button in android
application.

Create a new android application using android studio and give names as ButtonExample. In
case if you are not aware of creating an app in android studio check this article Android Hello
World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown
below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="First Number" />
<EditText
android:id="@+id/firstNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Number"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/secondNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<Button
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Add" />
</LinearLayout>

If you observe above code we created one Button, two TextView controls and
two EditText controls in XML Layout file.

Once we are done with the creation of layout with required control, we need to load the XML
layout resource from our activity onCreate() callback method, for that open main activity file
MainActivity.java from \java\com.tutlane.buttonexample path and write the code like as
shown below.

MainActivity.java
package com.tutlane.buttonexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText firstNum = (EditText)findViewById(R.id.firstNum);
final EditText secNum = (EditText)findViewById(R.id.secondNum);
Button btnAdd = (Button)findViewById(R.id.addBtn);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(firstNum.getText().toString().isEmpty() ||
secNum.getText().toString().isEmpty())
{
Toast.makeText(getApplicationContext(), "Please fill all the fields",
Toast.LENGTH_SHORT).show();
}
else {
int num1 = Integer.parseInt(firstNum.getText().toString());
int num2 = Integer.parseInt(secNum.getText().toString());
Toast.makeText(getApplicationContext(), "SUM = " + (num1 + num2),
Toast.LENGTH_SHORT).show();
}
}
});
}
}

If you observe above code we are calling our layout using setContentView method in the
form of R.layout.layout_file_name in our activity file. Here our xml file name is
activity_main.xml so we used file name activity_main and we are getting the values from
two EditText controls on Button click and performing an addition operation.

Generally, during the launch of our activity, onCreate() callback method will be called by
the android framework to get the required layout for an activity.

Output of Android Button Example


When we run above example using android virtual device (AVD) we will get a result like as
shown below.
This is how we can use Button control in android applications to perform required operations
on button tap or click based on our requirements.
Android ImageButton with Examples
In android, Image Button is a user interface control that is used to display a button with an
image and to perform an action when a user clicks or taps on it.

By default, the ImageButton looks same as normal button and it performs an action when a user
clicks or touches it, but the only difference is we will add a custom image to the button instead of
text.

Following is the pictorial representation of using Image Buttons in android applications.

In android, we have different types of buttons available to use based on our requirements, those
are Button, ImageButton, ToggleButton, and RadioButton.

In android, we can add an image to the button by


using <ImageButton> attribute android:src in XML layout file or by using
the setImageResource() method.

In android, we can create ImageButton control in two ways either in the XML layout file or create
it in the Activity file programmatically.

Create ImageButton in XML Layout File


Following is the sample way to define ImageButton control in XML layout file in android
application.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android
"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/add_icon" />
</LinearLayout>
If you observe above code snippet, here we defined ImageButton control and we are showing
the image from drawable folder using android:src attribute in xml layout file.

Create ImageButton Control in Activity File


In android, we can create ImageButton control programmatically in activity file based on our
requirements.

Following is the example of creating ImageButton control dynamically in an activity file.

LinearLayout layout = (LinearLayout)findViewById(R.id.l_layout);


ImageButton btn = new ImageButton(this);
btn.setImageResource(R.drawable.add_icon);
layout.addView(btn);

Anndroid Handle ImageButton Click Events


Generally, whenever the user clicks on ImageButton, the ImageButton object will receives an
on-click event.

In android, we can define button click event in two ways either in XML layout file or create it
in Activity file programmatically.

Define ImageButton Click Event in XML Layout File


We can define click event handler for button by adding android:onClick attribute to
the <ImageButton> element in our XML layout file.

The value of android:onClick attribute must be the name of method which we need to call in
response to a click event and the Activity file which hosting XML layout must implement the
corresponding method.

Following is the example of defining a button click event using android:onClick attribute in XML
layout file.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android
"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/add_icon"
android:onClick="addOperation"/>
</LinearLayout>
In Activity that hosts our XML layout file, we need to implement click event method like as shown
below

/** Called when the user touches the button */


public void addOperation(View view) {
// Do something in response to button click
}

Define ImageButton Click Event in Activity File


In android, we can define ImageButton click event programmatically in Activity file rather than
XML layout file.

To define button click programmatically, create View.OnClickListener object and assign it to the
button by calling setOnClickListener(View.OnClickListener) like as shown below.

ImageButton btnAdd = (ImageButton)findViewById(R.id.addBtn);


btnAdd.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});
}
This is how we can handle ImageButton click events in android applications based on our
requirements.

Android ImageButton Control Attributes


Following are some of the commonly used attributes related to ImageButton control in android
applications.

Attribute Description

android:id It is used to uniquely identify the control

android:src It is used to specify the source file of an image

android:background It is used to set the background color for an image button control.

android:padding It is used to set the padding from left, right, top and bottom of the image button.

android:baseline It is used to set the offset of the baseline within the view.

Android ImageButton Control Example


Following is the example of defining a one ImageButton and two EditText controls
in LinearLayout to get the data of EditText controls when click on ImageButton in android
application.

Create a new android application using android studio and give names as ButtonExample. In
case if you are not aware of creating an app in android studio check this article Android Hello
World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown
below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android
"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent" android:id="@+id/l_layout">
<TextView
android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:text="First Number"/>
<EditText
android:id="@+id/firstNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10"/>
<TextView
android:id="@+id/secTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Number"
android:layout_marginLeft="100dp" />
<EditText
android:id="@+id/secondNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:ems="10" />
<ImageButton
android:id="@+id/addBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:src="@drawable/add_icon" />
</LinearLayout>
If you observe above code we created one ImageButton, two TextView controls and
two EditText controls in XML Layout file.

Once we are done with the creation of layout with required control, we need to load the XML
layout resource from our activity onCreate() callback method, for that open main activity
file MainActivity.java from \java\com.tutlane.buttonexample path and write the code like as
shown below.

MainActivity.java
package com.tutlane.buttonexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText firstNum = (EditText)findViewById(R.id.firstNum)
;
final EditText secNum = (EditText)findViewById(R.id.secondNum);
ImageButton btnAdd = (ImageButton)findViewById(R.id.addBtn);
btnAdd.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(firstNum.getText().toString().isEmpty() || secNum.ge
tText().toString().isEmpty())
{
Toast.makeText(getApplicationContext(), "Please fil
l all the fields", Toast.LENGTH_SHORT).show();
}
else {
int num1 = Integer.parseInt(firstNum.getText().toSt
ring());
int num2 = Integer.parseInt(secNum.getText().toStri
ng());
Toast.makeText(getApplicationContext(), "SUM = " +
(num1 + num2), Toast.LENGTH_SHORT).show();
}
}
});
}
}
If you observe above code we are calling our layout using setContentView method in the form
of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so
we used file name activity_main and we are getting the values from two EditText controls on
ImageButton click and performing an addition operation.

Generally, during the launch of our activity, the onCreate() callback method will be called by the
android framework to get the required layout for an activity.

Output of Android ImageButton Example


When we run the above example using an android virtual device (AVD) we will get a result like as
shown below.

This is how we can use ImageButton control in android applications to perform required
operations on ImageButton tap or click based on our requirements.
Android CheckBox with Examples
In android, CheckBox is a two-states button that can be either checked (ON) or unchecked (OFF) and it will
allow users to toggle between the two states (ON / OFF) based on the requirements.

Generally, we can use multiple CheckBox controls in android application to allow users to select one or
more options from the set of values.

Following is the pictorial representation of using CheckBox control in android applications.

By default, the android CheckBox will be in the OFF (Unchecked) state. We can change the default state of
CheckBox by using android:checked attribute.

In case, if we want to change the state of CheckBox to ON (Checked), then we need to set
android:checked = “true” in our XML layout file.

In android, we can create CheckBox control in two ways either in the XML layout file or create it in
the Activity file programmatically.

Create CheckBox in XML Layout File


Following is the sample way to define CheckBox control in XML layout file in android application.

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<CheckBox
android:id="@+id/chk1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Java" /> </RelativeLayout>
If you observe above code snippet, here we defined CheckBox control and setting CheckBox state ON
using android:checked attribute in xml layout file.

Create CheckBox Control in Activity File


In android, we can create CheckBox control programmatically in activity file based on our requirements.

Following is the example of creating a CheckBox control dynamically in an activity file.

LinearLayout layout = (LinearLayout)findViewById(R.id.l_layout);


CheckBox cb = new CheckBox(this);
cb.setText("Tutlane");
cb.setChecked(true);
layout.addView(cb);

This is how we can define CheckBox in XML layout file or programmatically in activity file based on our
requirements.

Handle Android CheckBox Click Events


Generally, whenever the user clicks on CheckBox to Select or Deselect the CheckBox object will receive an
on-click event.

In android, we can define the CheckBox click event in two ways either in the XML layout file or create it in
the Activity file programmatically.

Define CheckBox Click Event in XML Layout File


We can define a click event handler for button by adding the android:onClick attribute to the
<CheckBox> element in our XML layout file.

The value of android:onClick attribute must be the name of method which we need to call in response to
a click event and the Activity file which hosting XML layout must implement the corresponding method.

Following is the example of defining a CheckBox click event using android:onClick attribute in XML layout
file.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="@+id/chk1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Java"
android:onClick="onCheckBoxClick"/>
</LinearLayout>

In Activity that hosts our XML layout file, we need to implement click event method like as shown below.

public void onCheckboxClicked(View view) {


// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.chk1:
if (checked)
// Do your coding
else
// Do your coding
break;
// Perform your logic
}
}

Define CheckBox Click Event in Activity File


In android, we can define CheckBox click event programmatically in Activity file rather than XML layout file.

To define checkbox click event programmatically, create View.OnClickListener object and assign it to the
button by calling setOnClickListener(View.OnClickListener) like as shown below.

CheckBox chk = (CheckBox) findViewById(R.id.chk1);


chk.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean checked = ((CheckBox) v).isChecked();
// Check which checkbox was clicked
if (checked){
// Do your coding
}
else{
// Do your coding
}
}
});
This is how we can handle CheckBox click events in android applications based on our requirements.

Android CheckBox Control Attributes


The following are some of the commonly used attributes related to CheckBox control in android
applications.

Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of checkbox

android:gravity It is used to specify how to align the text like left, right, center, top, etc.

android:text It is used to set the text for a checkbox.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for checkbox control.

android:padding It is used to set the padding from left, right, top and bottom.

android:onClick It’s the name of the method to invoke when the checkbox clicked.

android:visibility It is used to control the visibility of control.

Android CheckBox Control Example


Following is the example of defining multiple CheckBox controls and one Button control in LinearLayout to
get the selected values of CheckBox controls when we click on Button in the android application.

Create a new android application using android studio and give names as CheckBoxExample. In case if you
are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="@+id/chkJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:text="Java"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Python"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Android"
android:onClick="onCheckboxClicked"/>
<CheckBox
android:id="@+id/chkAngular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="AngularJS"
android:onClick="onCheckboxClicked"/>
<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:text="Get Details" />
</LinearLayout>
If you observe above code we created a multiple CheckBox controls and one Button control in XML Layout
file.

Once we are done with the creation of layout with required controls, we need to load the XML layout
resource from our activity onCreate() callback method, for that open main activity file MainActivity.java
from \java\com.tutlane.checkboxexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.checkboxexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


CheckBox android, java, angular, python;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android = (CheckBox)findViewById(R.id.chkAndroid);
angular = (CheckBox)findViewById(R.id.chkAngular);
java = (CheckBox)findViewById(R.id.chkJava);
python = (CheckBox)findViewById(R.id.chkPython);
Button btn = (Button)findViewById(R.id.getBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String result = "Selected Courses";
if(android.isChecked()){
result += "\nAndroid";
}
if(angular.isChecked()){
result += "\nAngularJS";
}
if(java.isChecked()){
result += "\nJava";
}
if(python.isChecked()){
result += "\nPython";
}
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_S
HORT).show();
}
});
}
public void onCheckboxClicked(View view) {
boolean checked = ((CheckBox) view).isChecked();
String str="";
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.chkAndroid:
str = checked?"Android Selected":"Android Deselected";
break;
case R.id.chkAngular:
str = checked?"AngularJS Selected":"AngularJS Deselected";
break;
case R.id.chkJava:
str = checked?"Java Selected":"Java Deselected";
break;
case R.id.chkPython:
str = checked?"Python Selected":"Python Deselected";
break;
}
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show(
);
}
}

If you observe above code we are calling our layout using setContentView method in the form of
R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file
name activity_main and we are getting the status of CheckBox controls when they Select / Deselect and
getting the selected CheckBox control values on Button click.

Generally, during the launch of our activity, onCreate() callback method will be called by android
framework to get the required layout for an activity.

Output of Android CheckBox Example


When we execute the above example using the android virtual device (AVD) we will get a result like as
shown below.
If you observe above result, we are able to get the status of checkboxes while selecting / deselecting and
getting all the selected CheckBox values on button click.

This is how we can use CheckBox control in android applications to allow users to select one or more
options based on our requirements.
Android RadioButton with Examples
In android, Radio Button is a two-states button that can be either checked or unchecked and it’s the same
as CheckBox control, except that it will allow only one option to select from the group of options.

The user can press or click on the radio button to make it select. In android, CheckBox control allow users
to change the state of control either Checked or Unchecked but the radio button cannot be unchecked
once it is checked.

Generally, we can use RadioButton controls in an android application to allow users to select only one
option from the set of values.

Following is the pictorial representation of using RadioButton control in android applications.

In android, we use radio buttons with in a RadioGroup to combine multiple radio buttons into one group
and it will make sure that users can select only one option from the group of multiple options.

By default, the android RadioButton will be in OFF (Unchecked) state. We can change the default state of
RadioButton by using android:checked attribute.

In case, if we want to change the state of RadioButton to ON (Checked), then we need to set
android:checked = “true” in our XML layout file.

In android, we can create RadioButton control in two ways either in the XML layout file or create it in
the Activity file programmatically.

Create RadioButton in XML Layout File


Following is the sample way to define RadioButton control using RadioGroup in the XML layout file in the
android application.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"
android:checked="true"/>
</RelativeLayout>

If you observe above code snippet, here we defined RadioButton control and setting RadioButton state
ON using android:checked attribute in xml layout file.

Create RadioButton Control in Activity File


In android, we can create RadioButton control programmatically in activity file based on our
requirements.

Following is the example of creating a RadioButton control dynamically in activity file.

LinearLayout layout = (LinearLayout)findViewById(R.id.l_layout);


RadioButton rd = new RadioButton(this);
rd.setText("Tutlane");
rd.setChecked(true);
layout.addView(rd);

This is how we can define RadioButton in XML layout file or programmatically in activity file based on our
requirements.

Handle Android RadioButton Click Events


Generally, whenever the user click on RadioButton to Select or Deselect the RadioButton object will
receives an on-click event.

In android, we can define RadioButton click event in two ways either in the XML layout file or create it in
Activity file programmatically.

Define RadioButton Click Event in XML Layout File


We can define click event handler for button by adding the android:onClick attribute to the
<RadioButton> element in our XML layout file.

The value of android:onClick attribute must be the name of the method which we need to call in response
to a click event and the Activity file which hosting XML layout must implement the corresponding method.

Following is the example of defining a RadioButton click event using android:onClick attribute in XML
layout file.

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
</RelativeLayout>

In Activity that hosts our XML layout file, we need to implement click event method like as shown below.

public void onRadioButtonClicked(View view) {


// Is the view now checked?
boolean checked = ((RadioButton) view).isChecked();
// Check which RadioButton was clicked
switch(view.getId()) {
case R.id.chk1:
if (checked)
// Do your coding
else
// Do your coding
break;
// Perform your logic
}
}

Define RadioButton Click Event in Activity File


In android, we can define RadioButton click event programmatically in Activity file rather than XML layout
file.
To define RadioButton click event programmatically, create View.OnClickListener object and assign it to
the button by calling setOnClickListener(View.OnClickListener) like as shown below.

RadioButton rdb = (RadioButton) findViewById(R.id.radiobutton1);


rdb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
boolean checked = ((RadioButton) v).isChecked();
// Check which radiobutton was pressed
if (checked){
// Do your coding
}
else{
// Do your coding
}
}
});

This is how we can handle RadioButton click events in android applications based on our requirements.

Android RadioButton Control Attributes


Following are the some of commonly used attributes related to RadioButton control in android
applications.

Attribute Description

android:id It is used to uniquely identify the control

android:checked It is used to specify the current state of radio button

android:gravity It is used to specify how to align the text like left, right, center, top, etc.

android:text It is used to set the text for the radio button.

android:textColor It is used to change the color of text.

android:textSize It is used to specify the size of the text.

android:textStyle It is used to change the style (bold, italic, bolditalic) of text.

android:background It is used to set the background color for radio button control.
Attribute Description

android:padding It is used to set the padding from left, right, top and bottom.

android:onClick It’s the name of the method to invoke when the radio button clicked.

android:visibility It is used to control the visibility of control.

Android RadioButton Control Example


Following is the example of defining a multiple RadioButton controls, one TextView control and one
Button control in RelativeLayout to get the selected values of RadioButton controls when we click
on Button in the android application.

Create a new android application using android studio and give names as RadioButtonExample. In case if
you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:textSize="18dp"
android:text="Select Your Course"
android:textStyle="bold"
android:id="@+id/txtView"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/rdGroup"
android:layout_below="@+id/txtView">
<RadioButton
android:id="@+id/rdbJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Java"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Python"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Android"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbAngular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="AngularJS"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_below="@+id/rdGroup"
android:text="Get Course" />
</RelativeLayout>

If you observe above code we created a multiple RadioButton controls, one TextView control and
one Button control in XML Layout file.

Once we are done with the creation of layout with required controls, we need to load the XML layout
resource from our activity onCreate() callback method, for that open main activity file MainActivity.java
from \java\com.tutlane.radiobuttonexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.radiobuttonexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


RadioButton android, java, angular, python;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android = (RadioButton)findViewById(R.id.rdbAndroid);
angular = (RadioButton)findViewById(R.id.rdbAngular);
java = (RadioButton)findViewById(R.id.rdbJava);
python = (RadioButton)findViewById(R.id.rdbPython);
Button btn = (Button)findViewById(R.id.getBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String result = "Selected Course: ";
result+= (android.isChecked())?"Android":(angular.isChecked())
?"AngularJS":(java.isChecked())?"Java":(python.isChecked())?"Python":"";
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_S
HORT).show();
}
});
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
String str="";
// Check which radio button was clicked
switch(view.getId()) {
case R.id.rdbAndroid:
if(checked)
str = "Android Selected";
break;
case R.id.rdbAngular:
if(checked)
str = "AngularJS Selected";
break;
case R.id.rdbJava:
if(checked)
str = "Java Selected";
break;
case R.id.rdbPython:
if(checked)
str = "Python Selected";
break;
}
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show(
);
}
}

If you observe above code we are calling our layout using setContentView method in the form of
R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file
name activity_main and we are getting the status of RadiButton controls when they Select / Deselect
and getting selected RadioButton control value on Button click.

Generally, during the launch of our activity, onCreate() callback method will be called by the android
framework to get the required layout for an activity.

Output of Android RadioButton Example


When we run the above example using android virtual device (AVD) we will get a result like as shown
below.

If you observe the above result, we are able to select only one option from the set of values and getting
the selected RadioButton value on button click.
This is how we can use RadioButton control in android applications to allow users to select only one
option from a set of values based on our requirements.
Android RadioGroup with Examples
In android, Radio Group is used to group one or more radio buttons into separate groups based on our
requirements.

If we group Radio Buttons using RadioGroup, at a time only one item can be selected from the group of
radio buttons. In case, if we select one radio button that belongs to a radio group will unselect all other
previously selected radio buttons within the same group.

Initially, all the radio buttons of the radio group are in the unchecked state, once we select a radio button
then it’s not possible for us to uncheck it like CheckBox control.

Following is the pictorial representation of grouping RadioButton controls using RadioGroup in android
applications.

Generally, we use radio buttons within a RadioGroup to combine multiple Radio Buttons into one group
and it will make sure that user can select only one option from the group of multiple options.

Following is the sample way to define RadioButton control using RadioGroup in the XML layout file in the
android application.

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RadioButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Java"/>
</RadioGroup>
</RelativeLayout>
This is how we can define RadioButton controls in RadioGroup based on our requirements in android
applications.

Android RadioGroup Example


Following is the example of defining multiple RadioButton controls in RadioGroup, one TextView control
and one Button control in RelativeLayout to get the selected values of RadioButton controls when we click
on Button in the android application.

Create a new android application using android studio and give names as RadioButtonExample. In case if
you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_marginLeft="100dp"
android:textSize="18dp"
android:text="Select Your Course"
android:textStyle="bold"
android:id="@+id/txtView"/>
<RadioGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="@+id/rdGroup"
android:layout_below="@+id/txtView">
<RadioButton
android:id="@+id/rdbJava"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Java"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbPython"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Python"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbAndroid"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="Android"
android:onClick="onRadioButtonClicked"/>
<RadioButton
android:id="@+id/rdbAngular"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:layout_marginLeft="100dp"
android:text="AngularJS"
android:onClick="onRadioButtonClicked"/>
</RadioGroup>
<Button
android:id="@+id/getBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_below="@+id/rdGroup"
android:text="Get Course" />
</RelativeLayout>

If you observe above code we created a multiple RadioButton controls in RadioGroup,


one TextView control and one Button control in XML Layout file.

Once we are done with the creation of layout with required controls, we need to load the XML layout
resource from our activity onCreate() callback method, for that open main activity file MainActivity.java
from \java\com.tutlane.radiogroupexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.radiobuttonexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


RadioButton android, java, angular, python;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
android = (RadioButton)findViewById(R.id.rdbAndroid);
angular = (RadioButton)findViewById(R.id.rdbAngular);
java = (RadioButton)findViewById(R.id.rdbJava);
python = (RadioButton)findViewById(R.id.rdbPython);
Button btn = (Button)findViewById(R.id.getBtn);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String result = "Selected Course: ";
result+= (android.isChecked())?"Android":(angular.isChecked())
?"AngularJS":(java.isChecked())?"Java":(python.isChecked())?"Python":"";
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_S
HORT).show();
}
});
}
public void onRadioButtonClicked(View view) {
boolean checked = ((RadioButton) view).isChecked();
String str="";
// Check which radio button was clicked
switch(view.getId()) {
case R.id.rdbAndroid:
if(checked)
str = "Android Selected";
break;
case R.id.rdbAngular:
if(checked)
str = "AngularJS Selected";
break;
case R.id.rdbJava:
if(checked)
str = "Java Selected";
break;
case R.id.rdbPython:
if(checked)
str = "Python Selected";
break;
}
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show(
);
}
}

If you observe above code we are calling our layout using setContentView method in the form of
R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file
name activity_main and we are getting the status of RadioButton controls when they Select / Deselect
and getting selected RadioButton control value on Button click.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android
framework to get the required layout for an activity.

Output of Android RadioGroup Example


When we run the above example using an android virtual device (AVD) we will get a result like as shown
below.

If you observe the above result, we are able to select only one option from a set of values and getting the
selected RadioButton value on Button click.

This is how we can use RadioButton control in RadioGroup to allow users to select only one option from a
set of values in android applications.
Android ProgressBar with Examples
In android, ProgressBar is a user interface control that is used to indicate the progress of an operation. For
example, downloading a file, uploading a file.

Following is the pictorial representation of using a different type of progress bars in android applications.

By default the ProgressBar will be displayed as a spinning wheel, in case if we want to show it like a
horizontal bar then we need to change the style property to horizontal
like style="?android:attr/progressBarStyleHorizontal".

Create Android ProgressBar in XML Layout File


In android, we can create ProgressBar in XML layout file using <ProgressBar> element with different
attributes like as shown below

<ProgressBar
android:id="@+id/pBar3"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:minHeight="50dp"
android:minWidth="250dp"
android:max="100"
android:indeterminate="true"
android:progress="1" />

If you observe above code snippet, we defined a progress bar (<ProgressBar>) with different attributes,
those are
Attribute Description

android:id It is used to uniquely identify the control

android:minHeightIt is used to set the height of the progress bar.

android:minWidth It is used to set the width of the progress bar.

android:max It is used to set the maximum value of the progress bar.

It is used to set the default progress value between 0 and max. It must be an
android:progress
integer value.

In android, the ProgressBar supports two types of modes to show the progress, those are Determinate
and Indeterminate.

Android ProgressBar with Determinate Mode


Generally, we use the Determinate progress mode in progress bar when we want to show the quantity of
progress has occurred. For example, the percentage of file downloaded, number of records inserted into a
database, etc.

To use Determinate progress, we need to set the style of the progress bar to
Widget_ProgressBar_Horizontal or progressBarStyleHorizontal and set the amount of progress using
android:progress attribute.

Following is the example which shows a Determinate progress bar that is 50% complete.

<ProgressBar
android:id="@+id/pBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:max="100"
android:progress="50" />

By using setProgress(int) method, we can update the percentage of progress displayed in app or by
calling incrementProgressBy(int) method, we can increase the value of current progress completed based
on our requirements.

Generally, when the progress value reaches 100 then the progress bar is full. By using android:max
attribute we can adjust this default value.
Android ProgressBar with Indeterminate Mode
Generally, we use the Indeterminate progress mode in progress bar when we don’t know how long an
operation will take or how much work has done.

In indeterminate mode the actual progress will not be shown, only the cyclic animation will be shown to
indicate that some progress is happing like as shown in the above progress bar loading images.

By using progressBar.setIndeterminate(true) in activity file programmatically or using


android:indeterminate = “true” attribute in XML layout file, we can enable Indeterminate progress
mode.

Following is the example to set Indeterminate progress mode in an XML layout file.

<ProgressBar
android:id="@+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:indeterminate="true"/>

This is how we can define the Progress modes in ProgressBar based on our requirements in android
applications.

Android ProgressBar Control Attributes


The following are some of the commonly used attributes related to ProgressBar control in android
applications.

Attribute Description

android:id It is used to uniquely identify the control

android:max It is used to specify the maximum value of the progress can take

android:progress It is used to specify default progress value.

android:background It is used to set the background color for a progress bar.

android:indeterminate It is used to enable the indeterminate progress mode.


Attribute Description

android:padding It is used to set the padding for left, right, top or bottom of a progress bar.

Android ProgressBar Example


Following is the example of defining one ProgressBar control, one TextView control and one Button control
in RelativeLayout to start showing the progress in the progress bar on Button click in the android
application.

Create a new android application using android studio and give names as ProgressBarExample. In case if
you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<ProgressBar
android:id="@+id/pBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="200dp"
android:minHeight="50dp"
android:minWidth="200dp"
android:max="100"
android:indeterminate="false"
android:progress="0" />
<TextView
android:id="@+id/tView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/pBar"
android:layout_below="@+id/pBar" />
<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="130dp"
android:layout_marginTop="20dp"
android:text="Start Progress"
android:layout_below="@+id/tView"/>
</RelativeLayout>

If you observe above code we created a one Progress control, one TextView control and one Button control
in XML Layout file.

Once we are done with the creation of layout with required controls, we need to load the XML layout
resource from our activity onCreate() callback method, for that open main activity file MainActivity.java
from \java\com.tutlane.progressbarexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.progressbarexample;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


private ProgressBar pgsBar;
private int i = 0;
private TextView txtView;
private Handler hdlr = new Handler();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pgsBar = (ProgressBar) findViewById(R.id.pBar);
txtView = (TextView) findViewById(R.id.tView);
Button btn = (Button)findViewById(R.id.btnShow);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
i = pgsBar.getProgress();
new Thread(new Runnable() {
public void run() {
while (i < 100) {
i += 1;
// Update the progress bar and display the current
value in text view
hdlr.post(new Runnable() {
public void run() {
pgsBar.setProgress(i);
txtView.setText(i+"/"+pgsBar.getMax());
}
});
try {
// Sleep for 100 milliseconds to show the prog
ress slowly.
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}
});
}
}

If you observe above code we are calling our layout using setContentView method in the form of
R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file
name activity_main and we are trying to show the progress of task in progress bar on Button click.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android
framework to get the required layout for an activity.

Output of Android ProgressBar Example


When we run the above example using an android virtual device (AVD) we will get a result like as shown
below.
If you observe the above result, we are able to start showing the progress of the task in progress bar when
we click on Button in the android application.

This is how we can use ProgressBar control in android applications to show the progress of tasks or work
based on our requirements.
Android ListView with Examples
In android, ListView is a ViewGroup that is used to display the list of scrollable of items in multiple rows
and the list items are automatically inserted to the list using an adapter.

Generally, the adapter pulls data from sources such as an array or database and converts each item into a
result view and that’s placed into the list.

Following is the pictorial representation of listview in android applications.

Android Adapter
In android, Adapter will act as an intermediate between the data sources and adapter views such as
ListView, Gridview to fill the data into adapter views. The adapter will hold the data and iterates through an
items in data set and generate the views for each item in the list.

Generally, in android we have a different types of adapters available to fetch the data from different data
sources to fill the data into adapter views, those are

Adapter Description

ArrayAdapter It will expects an Array or List as input.

CurosrAdapter It will accepts an instance of cursor as an input.


Adapter Description

SimpleAdapterIt will accepts a static data defined in the resources.

It is a generic implementation for all three adapter types and it can be used
BaseAdapter
for ListView, Gridview or Spinners based on our requirements

Android ListView Example


Following is the example of creating a ListView using arrayadapter in android application.

Create a new android application using android studio and give names as ListView. In case if you are not
aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout 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:orientation="vertical">
<ListView
android:id="@+id/userlist"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>

Once we are done with creation of layout, now we will bind data to our ListView using ArrayAdapter, for
that open main activity file MainActivity.java from \java\com.tutlane.listview path and write the code
like as shown below.

MainActivity.java

package com.tutlane.listview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private ArrayAdapter aAdapter;
private String[] users = { "Suresh Dasari", "Rohini Alavala", "Trishika Da
sari", "Praveen Alavala", "Madav Sai", "Hamsika Yemineni"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.userlist);
aAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1,
users);
mListView.setAdapter(aAdapter);
}
}

If you observe above code, we are binding static array (users) details to ListView using ArrayAdapter and
calling our layout using setContentView method in the form of R.layout.layout_file_name. Here our xml
file name is activity_main.xml so we used file name activity_main.

Generally, during the launch of our activity, onCreate() callback method will be called by the android
framework to get the required layout for an activity.

Output of Android ListView Example


When we run above example using android virtual device (AVD) we will get a result like as shown below.
This is how we can bind data to ListView using ArrayAdapter in android applications based on our
requirements.

Android ListView with Custom Adapter Example


In previous example, we learned a simple way to bind data to ListView using ArrayAdapter in the android
application. Now we will see how to create our own custom adapter and bind data to ListView with
example.

For this, we need to create our own custom adapter class by extending with the BaseAdapter class and
create a class that will contain parameters for list row items.

Now create a new android application using an android studio and give names as ListView. In case if you
are not aware of creating an app in android studio check this article Android Hello World App.

Open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/user_list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:dividerHeight="1dp" />
</LinearLayout>

Now we need to create a layout for listview row items, for that right click on layouts folder  select
New  Layout resource file  Give name as list_row.xml and click OK. Now open newly created file
(list_row.xml) and write the code like as shown below

list_row.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dip" >
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="17dp" />
<TextView
android:id="@+id/designation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/name"
android:layout_marginTop="7dp"
android:textColor="#343434"
android:textSize="14dp" />
<TextView
android:id="@+id/location"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/designation"
android:layout_alignBottom="@+id/designation"
android:layout_alignParentRight="true"
android:textColor="#343434"
android:textSize="14dp" />
</RelativeLayout>
Now we need to create a custom class (ListItem.java) to represent each row in the list, for that right click
on java folder  select New  Java Class  Give name as ListItem.java and click OK. Open ListItem.java
file and write the code like as shown below

ListItem.java

package com.tutlane.listview;
/**
* Created by tutlane on 23-08-2017.
*/
public class ListItem {
private String name;
private String designation;
private String location;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
}

Now we need to create a custom adapter (CustomListAdapter.java) and extend it by using BaseAdapter.
In case if we are extending our class by using BaseAdapter, we need to override following methods from
BaseAdapter class.

Method Description

getCount() It will return total number of rows count in listview

getItem() It is used to specify the object data of each row

getItemId() It returns the id of each row item


Method Description

getView() It is used to return a view instance that represents a single row in ListView item.

To create custom adapter right-click on java folder  select New  Java Class  Give name as
CustomListAdapter.java and click OK.

Open CustomListAdapter.java file and write the code like as shown below

CustomListAdapter.java

package com.tutlane.listview;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
/**
* Created by tutlane on 23-08-2017.
*/
public class CustomListAdapter extends BaseAdapter {
private ArrayList<ListItem> listData;
private LayoutInflater layoutInflater;
public CustomListAdapter(Context aContext, ArrayList<ListItem> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(aContext);
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View v, ViewGroup vg) {
ViewHolder holder;
if (v == null) {
v = layoutInflater.inflate(R.layout.list_row, null);
holder = new ViewHolder();
holder.uName = (TextView) v.findViewById(R.id.name);
holder.uDesignation = (TextView) v.findViewById(R.id.designation);
holder.uLocation = (TextView) v.findViewById(R.id.location);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.uName.setText(listData.get(position).getName());
holder.uDesignation.setText(listData.get(position).getDesignation());
holder.uLocation.setText(listData.get(position).getLocation());
return v;
}
static class ViewHolder {
TextView uName;
TextView uDesignation;
TextView uLocation;
}
}

If you observe above class we are extending our custom adapter by using BaseAdapter and we override all
BaseAdapter methods in our custom adapter.

Now we need to combine all the custom classes in main activity file (MainActivity.java) to bind the data to
our listview.

Open main activity file (MainActivity.java) and write the code like as shown below.

MainActivity.java

package com.tutlane.listview;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList userList = getListData();
final ListView lv = (ListView) findViewById(R.id.user_list);
lv.setAdapter(new CustomListAdapter(this, userList));
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, lo
ng id) {
ListItem user = (ListItem) lv.getItemAtPosition(position);
Toast.makeText(MainActivity.this, "Selected :" + " " + user.ge
tName()+", "+ user.getLocation(), Toast.LENGTH_SHORT).show();
}
});
}
private ArrayList getListData() {
ArrayList<ListItem> results = new ArrayList<>();
ListItem user1 = new ListItem();
user1.setName("Suresh Dasari");
user1.setDesignation("Team Leader");
user1.setLocation("Hyderabad");
results.add(user1);
ListItem user2 = new ListItem();
user2.setName("Rohini Alavala");
user2.setDesignation("Agricultural Officer");
user2.setLocation("Guntur");
results.add(user2);
ListItem user3 = new ListItem();
user3.setName("Trishika Dasari");
user3.setDesignation("Charted Accountant");
user3.setLocation("Guntur");
results.add(user3);
return results;
}
}

If you observe above code we are building and binding data to ListView using our custom adapter and
calling our layout using setContentView method in the form of R.layout.layout_file_name. Here our xml
file name is activity_main.xml so we used file name activity_main.

Generally, during the launch of our activity, onCreate() callback method will be called by android
framework to get the required layout for an activity.

Output of Android Custom ListView Example


When we run the above example using an android virtual device (AVD) we will get a result like as shown
below.
This is how we can bind data to ListView using custom adapter in android applications based on our
requirements.
Android GridView with Examples
In android, Grid View is a ViewGroup that is used to display items in a two dimensional, scrollable grid
and grid items are automatically inserted to the gridview layout using a list adapter.

Generally, the adapter pulls data from sources such as an array or database and converts each item into a
result view and that’s placed into the list.

Following is the pictorial representation of GridView in android applications.

Android Adapter
In android, Adapter will act as an intermediate between the data sources and adapter views such
as ListView, Gridview to fill the data into adapter views. The adapter will hold the data and iterates through
items in the data set and generate the views for each item in the list.

Generally, in android we have a different types of adapters available to fetch the data from different data
sources to fill the data into adapter views, those are

Adapter Description

ArrayAdapter It will expect an Array or List as input.

CurosrAdapter It will accept an instance of a cursor as an input.


Adapter Description

SimpleAdapterIt will accept a static data defined in the resources.

It is a generic implementation for all three adapter types and it can be used
BaseAdapter
for ListView, Gridview or Spinners based on our requirements

Android GridView Example


Following is the simple example showing user details using GridView and showing the position of a
particular image when clicking on it in android applications.

Create a new android application using android studio and give names as GridView. In case if you are not
aware of creating an app in android studio check this article Android Hello World App.

Once we create an application, add some sample images to project /res/drawable directory to show the
images in GridView.

Now open an activity_main.xml file from /res/layout path and write the code like as shown below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="110dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center" />

Once we are done with creation of layout, we need to create a custom adapter (ImageAdapter.java) by
extending it using BaseExtender to show all the items in the grid, for that right click on java folder  Give
name as ImageAdapter.java and click OK.

Open ImageAdapter.java file and write the code like as shown below

ImageAdapter.java
package com.tutlane.gridview;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
/**
* Created by tutlane on 24-08-2017.
*/
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return thumbImages.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(200, 200));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
imageView.setImageResource(thumbImages[position]);
return imageView;
}
// Add all our images to arraylist
public Integer[] thumbImages = {
R.drawable.img1, R.drawable.img2,
R.drawable.img3, R.drawable.img4,
R.drawable.img5, R.drawable.img6,
R.drawable.img7, R.drawable.img8,
R.drawable.img1, R.drawable.img2,
R.drawable.img3, R.drawable.img4,
R.drawable.img5, R.drawable.img6,
R.drawable.img7, R.drawable.img8,
R.drawable.img1, R.drawable.img2,
R.drawable.img3, R.drawable.img4,
R.drawable.img5
};
}
If you observe above code we referred some images, actually those are the sample images which we added
in /res/drawable directory.

Now we will bind images to our GridView using our custom adapter (ImageAdapter.java), for that open
main activity file MainActivity.java from \java\com.tutlane.gridview path and write the code like as
shown below.

MainActivity.java

package com.tutlane.gridview
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gv = (GridView) findViewById(R.id.gvDetails);
gv.setAdapter(new ImageAdapter(this));
gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int positio
n, long id) {
Toast.makeText(MainActivity.this, "Image Position: " + positio
n, Toast.LENGTH_SHORT).show();
}
});
}
}

If you observe above code, we are binding image details to GridView using our custom adapter
(ImageAdapter.java) and calling our layout using setContentView method in the form of
R.layout.layout_file_name. Here our xml file name is activity_main.xml so we used file name
activity_main.

Generally, during the launch of our activity, onCreate() callback method will be called by android
framework to get the required layout for an activity.

Output of Android GridView Example


When we run above example using the android virtual device (AVD) we will get a result like as shown
below.

This is how we can bind images to GridView using Adapter in android applications based on our
requirements.

Android GridView Details Activity Example


In above example, we implemented an image gallery using gridview in android application. Now we will
extend the functionality of above example to show the selected grid image in full screen.

Now we need to create a new layout (image_details.xml) file in project /res/layout directory to show the
image details, for that right click on the layouts folder  select New  Layout resource file  Give name
as image_details.xml and click OK. Now open newly created file (image_details.xml) and write the code
like as shown below.

image_details.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView android:id="@+id/full_image_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>

Now we need to create a custom activity (FullImageActivity.java) to show the image details in our newly
created layout (image_details.xml) file, for that right click on java folder  select New  Java
Class  Give name as FullImageActivity.java and click OK.

Open FullImageActivity.java file and write the code like as shown below

FullImageActivity.java

package com.tutlane.gridview;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.ImageView;

/**
* Created by tutlane on 24-08-2017.
*/
public class FullImageActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.image_details);
// Get intent data
Intent i = getIntent();
// Get Selected Image Id
int position = i.getExtras().getInt("id");
ImageAdapter imageAdapter = new ImageAdapter(this);
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
imageView.setImageResource(imageAdapter.thumbImages[position]);
}
}

Now we need to include our newly created activity file (FullImageActivity.java) in AndroidManifest.xml
file like as shown below. For that, open AndroidManifest.xml file and write the code like as shown below

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

<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- FullImageActivity -->
<activity android:name=".FullImageActivity"></activity>
</application>
</manifest>

Now we need to modify gridview image click function in main activity file (MainActivity.java) to get image
details and show it in new activity.

Open main activity file (MainActivity.java) and write the code like as shown below.

MainActivity.java

package com.tutlane.gridview;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gv = (GridView) findViewById(R.id.gvDetails);
gv.setAdapter(new ImageAdapter(this));
gv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int positio
n, long id) {
// Sending image id to FullScreenActivity
Intent i = new Intent(getApplicationContext(), FullImageActivi
ty.class);
// passing array index
i.putExtra("id", position);
startActivity(i);
}
});
}
}

If you observe above code, we are getting the selected image details on image click and sending those
details to our newly created activity file to show the image in full screen.

Output of Android GridView Details Activity


Example
When we run above example using android virtual device (AVD) we will get a result like as shown below.

This is how we can build image gallery in gridview and show the selected image in android applications
based on our requirements.
Android ScrollView (Horizontal, Vertical)
with Examples
In android, ScrollView is a kind of layout that is useful to add vertical or horizontal scroll bars to the
content which is larger than the actual size of layouts such as linearlayout, relativelayout, framelayout, etc.

Generally, the android ScrollView is useful when we have content that doesn’t fit our android app layout
screen. The ScrollView will enable a scroll to the content which is exceeding the screen layout and allow
users to see the complete content by scrolling.

The android ScrollView can hold only one direct child. In case, if we want to add multiple views within the
scroll view, then we need to include them in another standard layout
like linearlayout, relativelayout, framelayout, etc.

To enable scrolling for our android applications, ScrollView is the best option but we should not use
ScrollView along with ListView or Gridview because they both will take care of their own vertical scrolling.

In android, ScrollView supports only vertical scrolling. In case, if we want to implement horizontal
scrolling, then we need to use a HorizontalScrollView component.

The android ScrollView is having a property called android:fillViewport, which is used to define whether the
ScrollView should stretch it’s content to fill the viewport or not.

Now we will see how to use ScrollView with linearlayout to enable scroll view to the content which is
larger than screen layout in android application with examples.

Android ScrollView Example


Following is the example of enabling vertical scrolling to the content which is larger than the layout screen
using an android ScrollView object.

Create a new android application using android studio and give names as ScrollViewExample. In case if
you are not aware of creating an app in android studio check this article Android Hello World App.

Once we create an application, open activity_main.xml file from \res\layout folder path and write the
code like as shown below.
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="false">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="@+id/loginscrn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="80dp"
android:text="ScrollView"
android:textSize="25dp"
android:textStyle="bold"
android:layout_gravity="center"/>
<TextView android:id="@+id/fstTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:text="Welcome to Tutlane"
android:layout_gravity="center"/>
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:text="Button One" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:text="Button Two" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:text="Button Three" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:text="Button Four" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:text="Button Five" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:text="Button Six" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:text="Button Seven" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:text="Button Eight" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="60dp"
android:text="Button Nine" />
</LinearLayout>
</ScrollView>

If you observe above code, we used a ScrollView to enable the scrolling for linearlayout whenever the
content exceeds layout screen.

Output of Android ScrollView Example


When we run the above example in android emulator we will get a result as shown below.
If you observe the above result, ScrollView provided a vertical scrolling for linearlayout whenever the
content exceeds the layout screen.

As we discussed, ScrollView can provide only vertical scrolling for the layout. In case, if we want to enable
horizontal scrolling, then we need to use HorizontalScrollView in our application.

We will see how to enable horizontal scrolling for the content which is exceeding the layout screen in the
android application.

Android HorizontalScrollView Example


Now open activity_main.xml file in your android application and write the code like as shown below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/androi
d"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fillViewport="true">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="150dp">
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button One" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Two" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Three" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Four" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Five" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Six" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Seven" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Eight" />
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button Nine" />
</LinearLayout>
</HorizontalScrollView>

If you observe above code, we used a HorizontalScrollView to enable horizontal scrolling


for linearlayout whenever the content exceeds layout screen.

Output of Android HorizontalScrollView Example


When we run the above example in the android emulator we will get a result like as shown below.
If you observe above result, HorizontalScrollView provided a horizontal scrolling
for linearlayout whenever the content exceeds the layout screen.

This is how we can enable scrolling for the content which exceeds layout screen using ScrollView and
HorizontalScrollView object based on our requirements.
Android DatePicker with Examples
In android, DatePicker is a control that will allow users to select the date by a day, month and year in our
application user interface.

If we use DatePicker in our application, it will ensure that the users will select a valid date.

Following is the pictorial representation of using a datepicker control in android applications.

Generally, in android DatePicker available in two modes, one is to show the complete calendar and another
one is to show the dates in spinner view.

Create Android DatePicker in XML Layout File


In android, we can create a DatePicker in XML layout file using <DatePicker> element with different
attributes like as shown below

<DatePicker android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

In anroid, the DatePicker supports a two types of modes, those are Calendar and Spinner to show the date
details in our application.
Android DatePicker with Calendar Mode
We can define android DatePicker to show only a calendar view by using
DatePicker android:datePickerMode attribute.

Following is the example of showing the DatePicker in Calendar mode.

<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="calendar"/>

The above code snippet will return the DatePicker in android like as shown below

If you observe the above result we got the DatePicker in calendar mode to select a date based on our
requirements.

Android DatePicker with Spinner Mode


If we want to show the DatePicker in spinner format like showing day, month and year separately to select
the date, then by using DatePicker android:datePickerMode attribute we can achieve this.

Following is the example of showing the DatePicker in Spinner mode.

<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"/>

The above code snippet will return the DatePicker in android like as shown below

If you observe the above result we got the DatePicker in both Spinner and Calendar modes to select the
date.

To get only spinner mode date selection, then we need to


set android:calendarViewShown="false" attribute in DatePicker control like as shown below.

<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"
android:calendarViewShown="false"/>

The above code will return the DatePicker like as shown below
If you observe the above result we got the DatePicker in spinner mode to select the date separately by day,
month and year.

This is how we can use DatePicker in different modes based on our requirements in android applications.

Android DatePicker Control Attributes


The following are some of the commonly used attributes related to DatePicker control in android
applications.

Attribute Description

android:id It is used to uniquely identify the control

android:datePickerModeIt is used to specify datepicker mode either spinner or calendar

android:background It is used to set the background color for the date picker.

It is used to set the padding for left, right, top or bottom of the date
android:padding
picker.

Android DatePicker Example


Following is the example of defining one DatePicker control, one TextView control and one Button control
in RelativeLayout to show the selected date on Button click in the android application.

Create a new android application using android studio and give names as DatePickerExample. In case if
you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<DatePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/datePicker1"
android:layout_marginLeft="100dp"
android:text="Get Date" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginLeft="100dp"
android:layout_marginTop="10dp"
android:textStyle="bold"
android:textSize="18dp"/>
</RelativeLayout>

If you observe above code we created a one DatePicker control, one TextView control and
one Button control in XML Layout file.

Once we are done with the creation of layout with required controls, we need to load the XML layout
resource from our activity onCreate() callback method, for that open main activity file MainActivity.java
from \java\com.tutlane.datepickerexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.datepickerexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


DatePicker picker;
Button btnGet;
TextView tvw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvw=(TextView)findViewById(R.id.textView1);
picker=(DatePicker)findViewById(R.id.datePicker1);
btnGet=(Button)findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvw.setText("Selected Date: "+ picker.getDayOfMonth()+"/"+ (pi
cker.getMonth() + 1)+"/"+picker.getYear());
}
});
}
}

If you observe above code we are calling our layout using setContentView method in the form of
R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file
name activity_main and we are trying to show the selected date of DatePicker on Button click.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android
framework to get the required layout for an activity.

Output of Android DatePicker Example


When we run the above example using an android virtual device (AVD) we will get a result like as shown
below.
If you observe the above result, we are getting the date from DatePicker when we click on Button in the
android application.

Now we will see another example of showing the DatePicker control on EditText click event and get the
selected date value in the android application.

Android Show DatePicker on EditText Click


Example
Following is the example of open or popup datepicker dialog when we click on EditText control and get the
selected date value on Button click in the android application.

Create a new android application using android studio and give names as DatePickerExample. In case if
you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:ems="10"
android:hint="Enter Date" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_marginLeft="100dp"
android:text="Get Date" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginLeft="100dp"
android:layout_marginTop="10dp"
android:textStyle="bold"
android:textSize="18dp"/>
</RelativeLayout>

If you observe above code we created a one EditText control, one TextView control and one Button control
in XML Layout file.

Once we are done with the creation of layout with required controls, we need to load the XML layout
resource from our activity onCreate() callback method, for that open main activity file MainActivity.java
from \java\com.tutlane.datepickerexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.datepickerexample;
import android.app.DatePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {


DatePickerDialog picker;
EditText eText;
Button btnGet;
TextView tvw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvw=(TextView)findViewById(R.id.textView1);
eText=(EditText) findViewById(R.id.editText1);
eText.setInputType(InputType.TYPE_NULL);
eText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int day = cldr.get(Calendar.DAY_OF_MONTH);
int month = cldr.get(Calendar.MONTH);
int year = cldr.get(Calendar.YEAR);
// date picker dialog
picker = new DatePickerDialog(MainActivity.this,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, i
nt monthOfYear, int dayOfMonth) {
eText.setText(dayOfMonth + "/" + (monthOfYear
+ 1) + "/" + year);
}
}, year, month, day);
picker.show();
}
});
btnGet=(Button)findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvw.setText("Selected Date: "+ eText.getText());
}
});
}
}

If you observe above code we are calling our layout using setContentView method in the form of
R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file
name activity_main and we are trying to show the DatePicker on EditText click, get the selected date
of EditText control on Button click.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android
framework to get the required layout for an activity.

Output of Android Show DatePicker on EditText


Click Example
When we run the above example using an android virtual device (AVD) we will get a result like as shown
below.
If you observe the above result, we are able to open the DatePicker on EditText click and showing the
selected date value in EditText control and getting EditText control value on Button click in the android
application.

This is how we can use DatePicker control in android applications to pick the date based on our
requirements.
Android TimePicker with Examples
In android, TimePicker is a widget for selecting the time of day, in either 24-hour or AM/PM mode.

If we use TimePicker in our application, it will ensure that the users will select a valid time for the day.

Following is the pictorial representation of using a timepicker control in android applications.

Generally, in android TimePicker available in two modes, one is to show the time in clock mode and
another one is to show the time in spinner mode.

Create Android DatePicker in XML Layout File


In android, we can create a TimePicker in XML layout file using <TimePicker> element with different
attributes like as shown below

<TimePicker android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

In anroid, the TimePicker supports a two types of modes, those are Clock and Spinner to show the date
details in our application.
Android TimePicker with Clock Mode
We can define android TimePicker to show time in clock format by using
TimePicker android:timePickerMode attribute.

Following is the example of showing the TimePicker in Clock mode.

<TimePicker android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="clock" />

The above code will return the TimePicker like as shown below.

If you observe the above result we got the TimePicker in clock mode to select a time in Hours and
Minutes based on our requirements.

Android TimePicker with Spinner Mode


If we want to show the TimePicker in spinner format like showing hours and minutes separately to select
the time, then by using TimePicker android:timePickerMode attribute we can achieve this.

Following is the example of showing the TimePicker in spinner mode.

<TimePicker
android:id="@+id/datePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner"/>
The above code will return the TimePicker like as shown below

If you observe the above result we got the TimePicker in spinner mode to select the time in Hours and
Minutes.

We can change the TimePicker in spinner mode to AM / PM format instead of 24 Hours format by using
the setIs24HourView(true) method in Activity file like as shown below.

TimePicker picker=(TimePicker)findViewById(R.id.timePicker1);
picker.setIs24HourView(true);

The above code will return the TimePicker like as shown below

If you observe the above result we got the TimePicker with AM / PM format in spinner mode to select the
time separately by hours, minutes and AM/PM.

This is how we can use TimePicker in different modes based on our requirements in android applications.
Android TimePicker Control Attributes
The following are some of the commonly used attributes related to TimePicker control in android
applications.

Attribute Description

android:id It is used to uniquely identify the control

android:timePickerModeIt is used to specify timepicker mode, either spinner or clock

android:background It is used to set the background color for the date picker.

It is used to set the padding for left, right, top or bottom of the date
android:padding
picker.

Android TimePicker Example


Following is the example of defining one TimePicker control, one TextView control and one Button control
in RelativeLayout to show the selected time in AM / PM format on Button click in the android application.

Create a new android application using android studio and give names as TimePickerExample. In case if
you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TimePicker
android:id="@+id/timePicker1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/timePicker1"
android:layout_marginTop="10dp"
android:layout_marginLeft="160dp"
android:text="Get Date" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginLeft="120dp"
android:layout_marginTop="10dp"
android:textStyle="bold"
android:textSize="18dp"/>
</RelativeLayout>

If you observe above code we created a one TimePicker control, one TextView control and
one Button control in XML Layout file.

Once we are done with the creation of layout with required controls, we need to load the XML layout
resource from our activity onCreate() callback method, for that open main activity file MainActivity.java
from \java\com.tutlane.timepickerexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.timepickerexample;
import android.os.Build;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class MainActivity extends AppCompatActivity {


TimePicker picker;
Button btnGet;
TextView tvw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvw=(TextView)findViewById(R.id.textView1);
picker=(TimePicker)findViewById(R.id.timePicker1);
picker.setIs24HourView(true);
btnGet=(Button)findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int hour, minute;
String am_pm;
if (Build.VERSION.SDK_INT >= 23 ){
hour = picker.getHour();
minute = picker.getMinute();
}
else{
hour = picker.getCurrentHour();
minute = picker.getCurrentMinute();
}
if(hour > 12) {
am_pm = "PM";
hour = hour - 12;
}
else
{
am_pm="AM";
}
tvw.setText("Selected Date: "+ hour +":"+ minute+" "+am_pm);
}
});
}
}

If you observe the above code, we are calling our layout using setContentView method in the form of
R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used file
name activity_main and we are trying to show the selected time of TimePicker in AM / PM format
on Button click.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android
framework to get the required layout for an activity.
Output of Android TimePicker Example
When we run the above example using an android virtual device (AVD) we will get a result like as shown
below.

If you observe the above result, we are getting the time from TimePicker in AM / PM format when we click
on Button in the android application.

Now we will see another example of showing the TimePicker control on the EditText click event and get the
selected time value in the android application.
Androd Show TimePicker on EditText Click
Example
Following is the example of open or popup timepicker dialog when we click on EditText control and get the
selected time value on Button click in the android application.

Create a new android application using android studio and give names as TimePickerExample. In case if
you are not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="150dp"
android:ems="10"
android:hint="Enter Time" />
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_marginLeft="100dp"
android:text="Get Date" />
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button1"
android:layout_marginLeft="100dp"
android:layout_marginTop="10dp"
android:textStyle="bold"
android:textSize="18dp"/>
</RelativeLayout>

If you observe above code we created a one EditText control, one TextView control and one Button control
in XML Layout file.
Once we are done with the creation of layout with required controls, we need to load the XML layout
resource from our activity onCreate() callback method, for that open main activity file MainActivity.java
from \java\com.tutlane.timepickerexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.timepickerexample;
import android.app.TimePickerDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {


TimePickerDialog picker;
EditText eText;
Button btnGet;
TextView tvw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvw=(TextView)findViewById(R.id.textView1);
eText=(EditText) findViewById(R.id.editText1);
eText.setInputType(InputType.TYPE_NULL);
eText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Calendar cldr = Calendar.getInstance();
int hour = cldr.get(Calendar.HOUR_OF_DAY);
int minutes = cldr.get(Calendar.MINUTE);
// time picker dialog
picker = new TimePickerDialog(MainActivity.this,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker tp, int sHour, in
t sMinute) {
eText.setText(sHour + ":" + sMinute);
}
}, hour, minutes, true);
picker.show();
}
});
btnGet=(Button)findViewById(R.id.button1);
btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tvw.setText("Selected Time: "+ eText.getText());
}
});
}
}

If you observe above code we are calling our layout using setContentView method in the form
of R.layout.layout_file_name in our activity file. Here our xml file name is activity_main.xml so we used
file name activity_main and we are trying to show the TimePicker on EditText click, get the selected date
of EditText control on Button click.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android
framework to get the required layout for an activity.

Output of Androd Show TimePicker on EditText


Click Example
When we run the above example using an android virtual device (AVD) we will get a result like as shown
below.
If you observe the above result, we are able to open the TimePicker on EditText click and showing the
selected date value in EditText control and getting the EditText control value on Button click in the android
application.

This is how we can use TimePicker control in android applications to pick the time based on our
requirements.
Android Custom Toast with Examples
In android, Toast is a small popup notification that is used to display information about the operation
which we performed in our app. The Toast will show the message for a small period of time and it will
disappear automatically after a timeout.

Generally, the size of Toast will be adjusted based on the space required for the message and it will be
displayed on the top of the main content of activity for a short period of time.

To know more about creation of Toast in android applications, check this Android Toast with Examples.

Generally, the Toast notification in android will be displayed with simple text like as shown in above image.
In android, we can customize the layout of our toast notification to change the appearance of based on
requirements like include images in toast notification or change the background color of toast notification,
etc.

Following is the pictorial representation of using Custom Toast notification in android applications.

To customize the appearance of Toast notification, we need to create a custom layout in our XML or
application code and pass the root View object to the setView(View) method.

Create a Custom Toast in Android


To create a custom Toast notification in android, we need to define a custom View layout in XML, for that
create a custom XML file (custom_toast.xml) in layout (/layout) folder and write the code like as shown
below.

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_container"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:background="#80CC28">
<ImageView android:src="@drawable/ic_notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp" />
<TextView android:id="@+id/txtvw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="13dp"
android:textColor="#FFF"
android:textStyle="bold"
android:textSize="15dp" />
</LinearLayout>

To use this custom layout as Toast notification in our android application, we need to inflate the layout
using following code.

LayoutInflater inflater = getLayoutInflater();


View layout = inflater.inflate(R.layout.custom_toast, (ViewGroup) findViewById
(R.id.custom_toast_layout));
TextView tv = (TextView) layout.findViewById(R.id.txtvw);
tv.setText("Custom Toast Notification");
Toast toast = new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();

If you observe above code, we created an instance of LayoutInflater with getLayoutInflater(), and then
inflate our XML layout using inflate(int, ViewGroup). Here the first parameter is the layout resource ID
and the second is the root View and this inflated layout will help us to find the View objects in the layout.
After that we created a new Toast with Toast(Context) and set required properties of the toast, then we
call setView(View) and pass it to the inflated layout.

Once we are done with required configurations, then we can show the custom toast notification by calling
show() method.

Now we will see how to implement a custom Toast notification in android applications with examples.
Android Custom Toast Example
Create a new android application using android studio and give names as ToastExample. In case if you are
not aware of creating an app in android studio check this article Android Hello World App.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
android:id="@+id/btnShow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Custom Toast"
android:layout_marginTop="150dp" android:layout_marginLeft="110dp"/>
</LinearLayout>

If you observe above code we created a one Button control in XML Layout file to show the custom
toast notification when we click on Button.

Now we need to create a custom layout for our toast notification, for that create a new XML file
(custom_toast.xml) in /layout folder and write the code like as shown below.

Custom_toast.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/custom_toast_layout"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:background="#80CC28">
<ImageView android:src="@drawable/ic_notification"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp" />
<TextView android:id="@+id/txtvw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="13dp"
android:textColor="#FFF"
android:textStyle="bold"
android:textSize="15dp" />
</LinearLayout>

If you observe above code we are loading image (ic_notification) from drawable folder so you need to
add your icon in drawable folder to show it in notification.

Once we are done with the creation of layout with required controls, we need to load the XML layout
resource from our activity onCreate() callback method, for that open main activity file MainActivity.java
from \java\com.tutlane.toastexample path and write the code like as shown below.

MainActivity.java

package com.tutlane.customtoastexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button)findViewById(R.id.btnShow);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast, (ViewGro
up) findViewById(R.id.custom_toast_layout));
TextView tv = (TextView) layout.findViewById(R.id.txtvw);
tv.setText("Custom Toast Notification");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 100);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
}
});
}
}

If you observe above code we are calling our custom toast notification by using LayoutInflater object and
showing a toast notification on Button click.

Generally, during the launch of our activity, the onCreate() callback method will be called by the android
framework to get the required layout for an activity.

Output of Android Custom Toast Example


When we run above example using an android virtual device (AVD) we will get a result like as shown below.

If you observe above result we created a custom toast notification and showing it on Button click based on
our requirements.

This is how we can create custom toast notifications in android applications based on our requirements.

You might also like