Chapter 4
Chapter 4
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
The android framework will allow us to use either or both of these methods to define our
application’s UI.
Following is the example of defining UI controls (TextView, EditText, Button) in the XML
file (activity_main.xml) using LinearLayout.
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.
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.
Following is the example of setting width and height for View and ViewGroup elements in
the XML layout file.
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.
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.
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.
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.
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.
To know more about Radio Button in android check this, Android Radio Button with
Examples.
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.
If you observe above code snippet, here we defined a TextView control in xml layout file to
display the text in android application.
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.
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.
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;
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.
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 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.
If you observe above code snippet, here we defined AutoCompleteTextView control in xml
layout file.
l_layout.addView(actv);
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.
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.
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;
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.
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.
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.
Following is the example to get text of EditText control programmatically in activity file
using getText() method.
Attribute Description
android:gravity It is used to specify how to align the text like left, right, center, top, etc.
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: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:typeface It is used to specify the Typeface (normal, sans, serif, monospace) for the text
android:inputType It is used to specify the type of text being placed in text fields.
android:editable If we set false, EditText won't allow us to enter or modify the text
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;
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.
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.
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.
<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.
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.
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.
In Activity that hosts our XML layout file, we need to implement click event method like as
shown below
This is how we can handle button click events in android applications based on our
requirements.
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;
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.
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.
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 create ImageButton control in two ways either in the XML layout file or create
it in the Activity file programmatically.
In android, we can define button click event in two ways either in XML layout file or create it
in Activity file programmatically.
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.
To define button click programmatically, create View.OnClickListener object and assign it to the
button by calling setOnClickListener(View.OnClickListener) like as shown below.
Attribute Description
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.
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;
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.
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.
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.
This is how we can define CheckBox in XML layout file or programmatically in activity file based on our
requirements.
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.
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.
In Activity that hosts our XML layout file, we need to implement click event method like as shown below.
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.
Attribute Description
android:gravity It is used to specify how to align the text like left, right, center, top, etc.
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.
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
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;
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.
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.
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.
If you observe above code snippet, here we defined RadioButton control and setting RadioButton state
ON using android:checked attribute in xml layout file.
This is how we can define RadioButton in XML layout file or programmatically in activity file based on our
requirements.
In android, we can define RadioButton click event in two ways either in the XML layout file or create it in
Activity file programmatically.
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.
In Activity that hosts our XML layout file, we need to implement click event method like as shown below.
This is how we can handle RadioButton click events in android applications based on our requirements.
Attribute Description
android:gravity It is used to specify how to align the text like left, right, center, top, etc.
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.
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
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;
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.
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.
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
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;
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.
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".
<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
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.
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.
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.
Attribute Description
android:max It is used to specify the maximum value of the progress can take
android:padding It is used to set the padding for left, right, top or bottom of a progress bar.
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
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;
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.
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.
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
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
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
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.
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
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
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;
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.
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.
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
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
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
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;
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.
This is how we can bind images to GridView using Adapter in android applications based on our
requirements.
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;
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.
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.
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
If you observe above code, we used a ScrollView to enable the scrolling for linearlayout whenever the
content exceeds 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.
activity_main.xml
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.
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.
<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.
<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.
<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.
<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.
Attribute Description
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.
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
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;
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.
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.
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
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;
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.
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.
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.
<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.
<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.
<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: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.
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
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;
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
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;
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.
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.
To use this custom layout as Toast notification in our android application, we need to inflate the layout
using following code.
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
<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
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;
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.
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.