0% found this document useful (0 votes)
80 views100 pages

MAD Unit-4

This document provides an overview of various user interface controls in Android, including TextView, EditText, Button, ImageButton, ToggleButton, and RadioButton. It details their attributes, usage in XML layout files, and examples of how to implement them in Java code. The document serves as a guide for designing user interfaces in Android applications.
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)
80 views100 pages

MAD Unit-4

This document provides an overview of various user interface controls in Android, including TextView, EditText, Button, ImageButton, ToggleButton, and RadioButton. It details their attributes, usage in XML layout files, and examples of how to implement them in Java code. The document serves as a guide for designing user interfaces in Android applications.
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
You are on page 1/ 100

Unit 4

Designing User Interface with View

Android TextView
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

4.1 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

android:autoLink It will automatically found and convert URLs and email 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.

android:gravity It is used to specify how to align the text by the view's x and y-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

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


for the text.

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

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


t

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 TextView in Layout File

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:padding="@dimen/padding_medium"
android:text="@string/hello_world"
tools:context=".MainActivity" />

</RelativeLayout>

Output
Android Edit Text

EditText is a Widget of user interface (UI) used to retrieve and modify text data from a
user in an Android app

XML Attributes of EditText


Attributes Description

android:id It is used to uniquely identify the element

android:width It is used to set the width of EditText in pixels

android:hight It is used to set the height of EditText in pixels

android:text It is used to set the text value inside the EditText

android:inputType It is used to mention what type of value should pass in


EditText, like plain text, email, password, etc

android:hint It is used to highlight what should be input when text is


empty

android:gravity gravity is used to align the text like left, right, center, top

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

android:textStyle It is used to set the text style like bold, italic, bold italic, etc.

android:textColor It is used to set the color of the text

android:background It is used to set the background of your EditText


android:backgroundTi It is used to set tint to the background of your element
nt

android:maxWidth It is used to set the maximum width of View in pixel

android:minWidth It is used to set the minimum width of View in pixel

android:drawableStart It is used to set the drawable to be drawn to the start of View

android:drawableEnd It is used to set the drawable to be drawn to the end of View

android:drawableBotto It is used to set the drawable to be drawn to the bottom of


m View

android:drawableLeft It is used to set the drawable to be drawn to the left of View

android:drawableRight It is used to set the drawable to be drawn to the right of View

android:drawablePadd It is used to set the drawable to be drawn from the set


ing padding of View

Example of using EditText


1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
2. xmlns:app="http://schemas.android.com/apk/res-auto"
3. xmlns:tools="http://schemas.android.com/tools"
4. android:layout_width = "match_parent"
5. android:layout_height = "match_parent"
6. tools:context = "example.javatpoint.com.edittext.MainActivity">
7. <EditText
8. android:id = "@+id/editText"
9. android:layout_width = "wrap_content"
10. android:layout_height = "wrap_content"
11. android:inputType = "text" />
12.
13. </RelativeLayout>

How you retrieve value from EditText in Java Class


Following is the code to retrieve the value from EditText in your Java class.

1. EditText edittext = findViewById(R.id.editText);


2. String value=edittext.getText().toString();

Android Button
In android, Button is a user interface control that is used to perform an action whenever
the user clicks or tap on it.
Android Button represents a push-button. The android.widget.Button is subclass of
TextView class and CompoundButton is the subclass of Button class.
Generally, Buttons in android will contain a text or an icon or both and perform an action
when the user touches it.

Output of Android Button Example


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>

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();

});

Android ImageButton
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.

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.

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 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.

The ToggleButton is useful for the users to change the settings between two states either ON or
OFF.
It is beneficial if user have to change the setting between two states. It can be used to
On/Off Sound, Wifi, Bluetooth etc.
We can add a ToggleButton to our application layout by using the ToggleButton object.

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


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

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

Android ToggleButton Control Attributes

The following are some of the commonly used attributes related to ToggleButton 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 toggle 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.

android:textOn It is used to set the text when the toggle button is in the ON
/ Checked state.

android:textOff It is used to set the text when the toggle button is in the
OFF / Unchecked state.

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 toggle 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 text.

android:drawableRight It’s drawable to be drawn to the right of the text.

android:drawableLeft It’s drawable to be drawn to the left of text.

Output of Android ToggleButton Example


When we run above example using an android virtual device (AVD) we will get a result like as shown
below.
This is how we can use ToggleButton control in android applications to switch the settings between
two states either ON or OFF based on our requirements.

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">

<ToggleButton

android:id="@+id/toggle1"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_marginLeft="100dp"

android:layout_marginTop="120dp"

android:checked="true"

android:textOff="OFF"

android:textOn="ON"/>

<ToggleButton

android:id="@+id/toggle2"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_alignBottom="@+id/toggle1"

android:layout_toRightOf="@+id/toggle1"

android:textOff="OFF"

android:textOn ="ON"/>

<Button

android:id="@+id/getBtn"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:layout_marginLeft="150dp"

android:layout_marginTop="200dp"

android:text="Submit" />

</RelativeLayout>

If you observe above code we defined a two ToggleButton controls and one Button control in
RelativeLayout to get the state of ToggleButton controls when we click on Button 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.togglebuttonexample path and write the code like as
shown below.

MainActivity.java

package com.tutlane.togglebuttonexample;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

import android.widget.ToggleButton;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

final ToggleButton tb1 = (ToggleButton)findViewById(R.id.toggle1);

final ToggleButton tb2 = (ToggleButton)findViewById(R.id.toggle2);


Button btnGet = (Button)findViewById(R.id.getBtn);

btnGet.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

Toast.makeText(getApplicationContext(), "Toggle Button1 - " + tb1.getText().toString() + " \n"


+ "Toggle Button2 - " + tb2.getText().toString(),Toast.LENGTH_SHORT).show();

});

RadioButton & RadioGroup In Android Studio


In Android, RadioButton are mainly used together in a RadioGroup. In
RadioGroup checking the one radio button out of several radio button added in it
will automatically unchecked all the others. It means at one time we can checked
only one radio button from a group of radio buttons which belong to same radio
group.

RadioButon is a two state button that can be checked or unchecked. If a radio


button is unchecked then a user can check it by simply clicking on it. Once a
RadiaButton is checked by user it can’t be unchecked by simply pressing on the
same button. It will automatically unchecked when you press any other
RadioButton within same RadioGroup.

Important Note: RadioGroup is a widget used in Android for the grouping of


radio buttons and provide the feature of selecting only one radio button from the
set. When a user try to select any other radio button within same radio group the
previously selected radio button will be automatically unchecked.

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


** Output of Android RadioButton Example

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>
</RelativeLayout>
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);

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();
}
}
Android CheckBox
Android CheckBox is a type of two state button either checked or unchecked.

There can be a lot of usage of checkboxes. For example, it can be used to know the
hobby of the user, activate/deactivate the specific action etc.

Attributes of CheckBox:

1.id: id is an attribute used to uniquely identify a check box. Below we set the id
of a image button.
<CheckBox
android:id="@+id/simpleCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Simple CheckBox"/>

2. checked: checked is an attribute of check box used to set the current state of
a check box. The value should be true or false where true shows the checked
state and false shows unchecked state of a check box. The default value of
checked attribute is false. We can also set the current state programmatically.
Below is an example code in which we set true value for checked attribute that
sets the current state to checked.
<CheckBox
android:id="@+id/simpleCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Simple CheckBox"
android:checked="true"/> <!--set the current state of the check box-->
3. gravity: The gravity attribute is an optional attribute which is used to control
the alignment of the text in CheckBox like left, right, center, top, bottom,
center_vertical, center_horizontal etc.
Below we set the right and center_vertical gravity for the text of a check box.

<CheckBox

android:id="@+id/simpleCheckBox"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:text="Simple CheckBox"

android:checked="true"

android:gravity="right|center_vertical"/> <!-- gravity of the check box-->

4. text: text attribute is used to set the text in a check box. We can set the text in
xml as well as in the java class.

Below is the example code with explanation included in which we set the text
“Text Attribute Of Check Box” for a check box.

<CheckBox

android:id="@+id/simpleCheckBox"

android:layout_width="wrap_content"
android:layout_height="wrap_content"

android:checked="true"

android:text="Text Attribute Of Check Box"/> <!--displayed text of the check


box-->

5. textColor: textColor attribute is used to set the text color of a check box. Color
value is in form of “#argb”, “#rgb”, “#rrggbb”, or “#aarrggbb”.

6. textSize: textSize attribute is used to set the size of text of a check box. We
can set the text size in sp(scale independent pixel) or dp(density pixel).
7. textStyle: textStyle attribute is used to set the text style of the text of a check
box. The possible text styles are bold, italic and normal. If we need to use two or
more styles for a text view then “|” operator is used for that.\
8. background: background attribute is used to set the background of a check
box. We can set a color or a drawable in the background of a check box.

** Output of Checkbox program


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>

MainActivity.java

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.Toast;
import android.widget.Button;
import android.view.View;

import android.widget.Toast;
import android.os.Bundle;

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_SHORT).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();
}
}

ProgressBar Tutorial With Example In Android


Studio

In Android, ProgressBar is used to display the status of work being done like
analyzing status of work or downloading a file etc. In Android, by default a
progress bar will be displayed as a spinning wheel but If we want it to be
displayed as a horizontal bar then we need to use style attribute as horizontal. It
mainly use the “android.widget.ProgressBar” class.

ProgressBar code:
<ProgressBar

android:id="@+id/simpleProgressBar"

android:layout_width="wrap_content"

android:layout_height="wrap_content" />

Horizontal ProgressBar code:

<ProgressBar

android:id="@+id/simpleProgressBar"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

style="@style/Widget.AppCompat.ProgressBar.Horizontal"/>

Let's see a simple example to display progress bar in android.

1. ProgressDialog progressBar = new ProgressDialog(this);


2. progressBar.setCancelable(true);//you can cancel it by pressing back button
3. progressBar.setMessage("File downloading ...");
4. progressBar.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
5. progressBar.setProgress(0);//initially progress is 0
6. progressBar.setMax(100);//sets the maximum value 100
7. progressBar.show();//displays the progress bar

Attributes of ProgressBar In Android:

Now let’s discuss important attributes that helps us to configure a Progress bar in
xml file (layout).

1. id: id is an attribute used to uniquely identify a Progress bar.

<ProgressBar

android:id="@+id/simpleProgressBar"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

style="@style/Widget.AppCompat.ProgressBar.Horizontal"/>

2. max: max is an attribute used in android to define maximum value of the


progress can take. It must be an integer value like 100, 200 etc.

Below we set 100 maximum value for a progress bar.

<ProgressBar

android:id="@+id/simpleProgressBar"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

style="@style/Widget.AppCompat.ProgressBar.Horizontal"

android:max="100" /><!--set 100 maximum value for the progress bar-->

Set Max Value of ProgressBar In Java Class :

ProgressBar simpleProgressBar=(ProgressBar) findViewById(R.id.simpleProgressBar); // initiate the


progress bar

simpleProgressBar.setMax(100); // 100 maximum value for the progress bar


3. progress: progress is an attribute used in android to define the default
progress value between 0 and max. It must be an integer value.

Below we set the 100 max value and then set 50 default progress.

<ProgressBar

android:id="@+id/simpleProgressBar"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:max="100"

style="@style/Widget.AppCompat.ProgressBar.Horizontal"

android:progress="50"/><!--// 50 default progress value-->

Setting Progress Value of ProgressBar In Java Class :

ProgressBar simpleProgressBar=(ProgressBar)findViewById(R.id.simpleProgressBar); // initiate the


progress bar
simpleProgressBar.setMax(100); // 100 maximum value for the progress value

simpleProgressBar.setProgress(50); // 50 default progress value for the progress bar

4. progressDrawable: progress drawable is an attribute used in Android to set


the custom drawable for the progress mode.

Below we set a custom gradient drawable for the progress mode of a progress
bar. Before you try below code make sure to download a progress icon from the
web and add in your drawable folder.

Step 1: Add this code in activity_main.xml or main.xml inside layout.

<ProgressBar

android:id="@+id/simpleProgressBar"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:max="100"

android:progress="60"

android:layout_marginTop="100dp"

style="@style/Widget.AppCompat.ProgressBar.Horizontal"

android:progressDrawable="@drawable/custom_progress"/><!--custom progress drawable for progress


mode-->

Step 2: Create a new drawable resource xml in drawable folder and name it
custom_progress. Here add the below code which creates gradient effect in
progressbar.

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

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

<item>

<shape>

<gradient

android:endColor="#fff"
android:startColor="#1f1"

android:useLevel="true" />

</shape>

</item>

</layer-list>

5. background: background attribute is used to set the background of a


Progress bar. We can set a color or a drawable in the background of a Progress
bar.

Below we set the black color for the background of a Progress bar.

<ProgressBar

android:id="@+id/simpleProgressBar"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:max="100"

android:progress="50"

style="@style/Widget.AppCompat.ProgressBar.Horizontal"

android:background="#000"/><!-- black background color for progress bar-->


6. indeterminate: indeterminate attribute is used in Android to enable the
indeterminate mode. In this mode a progress bar shows a cyclic animation
without an indication of progress. This mode is used in application when we don’t
know the amount of work to be done. In this mode the actual working will not be
shown.

In below code we set the indeterminate to true.

<ProgressBar

android:id="@+id/simpleProgressBar"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:max="100"

android:progress="50"

android:background="#000"

android:padding="20dp" style="@style/Widget.AppCompat.ProgressBar.Horizontal"

android:indeterminate="true"/><!--true value for indeterminate-->


Setting indeterminate of ProgressBar In Java class:

ProgressBar simpleProgressBar=(ProgressBar)findViewById(R.id.simpleProgressBar); // initiate the


progress bar

simpleProgressBar.setBackgroundColor(Color.BLACK); // black background color for the progress bar

7. padding: padding attribute is used to set the padding from left, right, top or
bottom of ProgressBar.

● paddingRight: set the padding from the right side of the Progress bar.
● paddingLeft: set the padding from the left side of the Progress bar.
● paddingTop: set the padding from the top side of the Progress bar.
● paddingBottom: set the padding from the bottom side of the Progress
bar.
● Padding: set the padding from the all side’s of the Progress bar.

Below we set the 20dp padding from all the side’s of the Progress bar.

<ProgressBar

android:id="@+id/simpleProgressBar"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:max="100"

android:progress="50"
android:background="#000"

style="@style/Widget.AppCompat.ProgressBar.Horizontal"

android:padding="20dp"/><!--// 20dp padding from all the sides of the progress bar-->

In this example, I'm going to create 2 horizontal ProgressBar(s).

1. The first ProgressBar is put in Determinate mode. It displays a process which the percentage
of complete work is indicated.
2. The second ProgressBar is put in Indeterminate mode. It will show a progress for which you
cannot know the percentage of completed work.
**Output of Progress Bar
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>

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 progress slowly.

Thread.sleep(100);

} catch (InterruptedException e) {

e.printStackTrace();

}).start();

});

}
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

ArrayAdapter It will expects an Array or List as input.

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

SimpleAdapter It will accepts a static data defined in the resources.


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

SimpleAdapter in Android with Example


In Android, whenever we want to bind some data which we get from any data source
(e.g. ArrayList, HashMap, SQLite, etc.) with a UI component(e.g. ListView, GridView,
etc.) then Adapter comes into the picture. Basically Adapter acts as a bridge between
the UI component and data sources. Here Simple Adapter is one type of Adapter. It is
basically an easy adapter to map static data to views defined in our XML file(UI
component) and is used for customization of List or Grid items. Here we use an
ArrayList of Map (e.g. hashmap, mutable map, etc.) for data-backing. Each entry in an
ArrayList is corresponding to one row of a list. The Map contains the data for each row.
Now to display the row we need a view for which we used to specify a custom list item
file (an XML file).

General Syntax of SimpleAdapter


SimpleAdapter(Context context, List<? extends Map<String, ?>> data, int
resource, String[] from, int[] to)

4.2 Android Listview

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.
List of scrollable items can be displayed in Android using ListView. It helps you to displaying the data
in the form of a scrollable list. Users can then select any list item by clicking on it. ListView is default
scrollable so we do not need to use scroll View or anything else with ListView.

ListView is widely used in android applications. A very common example of ListView is your phone
contact book, where you have a list of your contacts displayed in a ListView and if you click on it then
user information is displayed.
Attributes of ListView:

1. id: id is used to uniquely identify a ListView.


Below is the id attribute’s example code with explanation included.
<!-- Id of a list view uniquely identify it-->
<ListView
android:id="@+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

2. divider: This is a drawable or color to draw between different list items.


Below is the divider example code with explanation included, where we
draw red color divider between different views.
<!--Divider code in ListView-->
<ListView
android:id="@+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#f00"
android:dividerHeight="1dp"
/>

3. dividerHeight: This specify the height of the divider between list items.
This could be in dp(density pixel),sp(scale independent pixel) or px(pixel).
In above example of divider we also set the divider height 1dp between the
list items. The height should be in dp,sp or px.
4. listSelector: listSelector property is used to set the selector of the
listView. It is generally orange or Sky blue color mostly but you can also
define your custom color or an image as a list selector as per your design.

Below is listSelector example code with explanation includes, where list


selector color is green, when you select any list item then that item’s
background color is green .
<!-- List Selector Code in ListView -->
<ListView
android:id="@+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#f00"
android:dividerHeight="1dp"
android:listSelector="#0f0"/> <!--list selector in green color-->

Android ListView Example

Output of Android ListView Example


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 Dasari",


"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);

GridView In Android
A GridView is a type of AdapterView that displays items in a two-dimensional
scrolling grid. Items are inserted into this grid layout from a database or from an
array. The adapter is used for displaying this data, setAdapter() method is used
to join the adapter with GridView. The main function of the adapter in GridView is
to fetch data from a database or array and insert each piece of data in an
appropriate item that will be displayed in GridView.
GridView is widely used in android applications. An example of GridView is your
default Gallery, where you have number of images displayed using grid.
Following is the pictorial representation of GridView in android applications.

Attributes of GridView:

1.id: id is used to uniquely identify a GridView.


Below is the id attribute’s example code with explanation included in which we
don’t specify the number of columns in a row that’s why the GridView behaves
like a ListView.
Below is the id attribute example code for Gridview:
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>

2.numColumns: numColumn define how many columns to show. It may be a


integer value, such as “5” or auto_fit.
auto_fit is used to display as many columns as possible to fill the available space
on the screen.
Important Note: If we don’t specify numColumn property in GridView it behaves
like a ListView with singleChoice.
Below is the numColumns example code where we define 4 columns to show in
the screen.
<!-- numColumns example code -->
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="4"/> <!-- numColumns set to 4-->

3. horizontalSpacing: horizontalSpacing property is used to define the default


horizontal spacing between columns. This could be in pixel(px),density pixel(dp)
or scale independent pixel(sp).
Below is the horizontalSpacing example code with explanation included where
horizontal spacing between grid items is 50 dp.
<!--Horizontal space example code in grid view-->>
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:horizontalSpacing="50dp"/><!--50dp horizontal space between grid items-->
4.verticalSpacing: verticalSpacing property used to define the default vertical
spacing between rows. This should be in px, dp or sp.
Below is the verticalSpacing example code with explanation included, where
vertical spacing between grid items is 50dp.
<!-- Vertical space between grid items code -->
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:verticalSpacing="50dp"/><!--50dp vertical space set between grid items-->
5.columnWidth: columnWidth property specifies the fixed width of each column.
This could be in px, dp or sp.
Below is the columnWidth example code. Here column width is 80dp and
selected item’s background color is green which shows the actual width of a grid
item.
Important Note: In the below code we also used listSelector property which
define color for selected item. Also to see the output of columnWidth using
listSelector we need to use Adapter which is our next topic. The below code is
not sufficient to show you the output.
<!--columnWidth in Grid view code-->
<GridView
android:id="@+id/simpleGridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3"
android:columnWidth="80dp"
android:listSelector="#0f0"/><!--define green color for selected item-->
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/gridView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="110dp"
android:numColumns="3"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center" />

import androidx.appcompat.app.AppCompatActivity;
import android.widget.CheckBox;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.GridView;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {


GridView gridView;

private String[] numbers = new String[] {


"1", "2", "3", "4", "5",
"6", "7", "8", "9", "10",};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.gridView1);

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


android.R.layout.simple_list_item_1, numbers);
gridView.setAdapter(adapter);
}}

ImageView In Android
In Android, ImageView class is used to display an image file in application. Image

file is easy to use but hard to master in Android, because of the various screen

sizes in Android devices. An android is enriched with some of the best UI design

widgets that allows us to build good looking and attractive UI based application.

Below is an ImageView code in XML:

Make sure to save lion image in drawable folder

<ImageView

android:id="@+id/simpleImageView"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:src="@drawable/lion" />
Attributes of ImageView:

Now let’s we discuss some important attributes that helps us to configure a

ImageView in your xml file.

1. id: id is an attribute used to uniquely identify a image view in android. Below is

the example code in which we set the id of a image view.

<ImageView

android:id="@+id/simpleImageView"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

/>

2. src: src is an attribute used to set a source file or you can say image in your

imageview to make your layout attractive.

Below is the example code in which we set the source of a imageview lion which

is saved in drawable folder.


<ImageView

android:id="@+id/simpleImageView"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:src="@drawable/lion" /><!--set the source of an image view-->

/set the source in java class

3. background: background attribute is used to set the background of a

ImageView. We can set a color or a drawable in the background of a ImageView.

Below is the example code in which we set the black color in the background and

an image in the src attribute of image view.

<ImageView

android:id="@+id/simpleImageView"

android:layout_width="fill_parent"
android:layout_height="wrap_content"

android:src="@drawable/lion"

android:background="#000"/><!--black color in background of a image view-->

4. padding: padding attribute is used to set the padding from left, right, top or

bottom of the Imageview.

● paddingRight: set the padding from the right side of the image view.

● paddingLeft: set the padding from the left side of the image view.

● paddingTop: set the padding from the top side of the image view.

● paddingBottom: set the padding from the bottom side of the image view.

● padding: set the padding from the all side’s of the image view.

Below is the example code of padding attribute in which we set the 30dp padding

from all the side’s of a image view.

<ImageView
android:id="@+id/simpleImageView"

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:background="#000"

android:src="@drawable/lion"

android:padding="30dp"/><!--set 30dp padding from all the sides-->

5. scaleType: scaleType is an attribute used to control how the image should be

re-sized or moved to match the size of this image view. The value for scale type

attribute can be fit_xy, center_crop, fitStart etc.

Below is the example code of scale type in which we set the scale type of image

view to fit_xy.

<ImageView

android:id="@+id/simpleImageView"
android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:src="@drawable/lion"

android:scaleType="fitXY"/><!--set scale type fit xy-->

Example of ImageView:

Step 1: Create a new project and name it ImageViewExample.

Step 2: Download two images lion and monkey from the web. Now save those
images in the drawable folder of your project.
Step 3: Now open res -> layout -> activity_main.xml (or) main.xml and add
following code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<ImageView
android:id="@+id/simpleImageViewLion"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:scaleType="fitXY"
android:src="@drawable/lion" />

<ImageView
android:id="@+id/simpleImageViewMonkey"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_below="@+id/simpleImageViewLion"
android:layout_marginTop="10dp"
android:scaleType="fitXY"
android:src="@drawable/monkey" />

</RelativeLayout>
ScrollView And Horizontal ScrollView in
android
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.

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.

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.
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.

Output of Android HorizontalScrollView Example

When we run the above example in the android emulator we will get a result like as shown below.

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

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

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.

Home Work-
Android Custom Toast
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.

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, (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.setGravity(Gravity.CENTER_VERTICAL, 0, 100);

toast.setDuration(Toast.LENGTH_LONG);

toast.setView(layout);

toast.show();

});

The LayoutInflater class is used to instantiate the contents of layout XML files into their
corresponding View objects.

In other words, it takes an XML file as input and builds the View objects from it.
Android DatePicker

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.

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:datePickerMode It is used to specify datepicker mode either spinner or


calendar

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

Methods of DatePicker
Let’s discuss some common methods of a datepicker which are used to configure
a DatePicker in our application.
1. setSpinnersShown(boolean shown):
This method is used to set whether the spinner of the date picker in shown or
not. In this method you have to set a Boolean value either true or false. True
indicates spinner is shown, false value indicates spinner is not shown. Default
value for this function is true.
Below we show the use of setSpinnerShown() function by setting false value.

DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker

simpleDatePicker.setSpinnersShown(false); // set false value for the spinner shown function

2. getDayOfMonth():
This method is used to get the selected day of the month from a date picker.
This method returns an integer value.
Below we get the selected day of the month from a date picker.

/*Add in Oncreate() funtion after setContentView()*/


DatePicker simpleDatePicker = (DatePicker) findViewById(R.id.simpleDatePicker); // initiate a date picker
int day = simpleDatePicker.getDayOfMonth(); // get the selected day of the month

3. getMonth():
This method is used to get the selected month from a date picker. This method
returns an integer value.
Below we get the selected month from a date picker.

DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker


int month = simpleDatePicker.getMonth(); // get the selected month

4. getYear():
This method is used to get the selected year from a date picker. This method
returns an integer value.
Below code is used to get the selected year from a date picker.

DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker


int year = simpleDatePicker.getYear(); // get the selected year

5. getFirstDayOfWeek():
This method is used to get the first day of the week. This method returns an
integer value.
Below code is used to get the first day of the week.

DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker

int firstDay=simpleDatePicker.getFirstDayOfWeek(); // get the first day of the week

Attributes of DatePicker
Now let’s we discuss some important attributes that helps us to configure a
DatePicker in your XML file (layout).
1. id: id is an attribute used to uniquely identify a date picker.

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

2. datePickerMode: This attribute is used to set the Date Picker in mode either
spinner or calendar. Default mode is calendar but this mode is not used after api
level 21, so from api level 21 you have to set the mode to spinner.
Below is an example code in which we set the mode to spinner for a date picker.

<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner" /> <!-- spinner mode of a date picker -->

3. background: background attribute is used to set the background of a date


picker. We can set a color or a drawable image in the background.
Below we set the red color for the background of a date picker.

<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"
android:background="#f00"/> <!-- red color for the background of the date picker -->
Setting background of DatePicker In Java Class:
DatePicker simpleDatePicker=(DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker
simpleDatePicker.setBackgroundColor(Color.RED); // red color for the background of a date picker

4. padding: padding attribute is used to set the padding from left, right, top or
bottom for a date picker.

● paddingRight: set the padding from the right side of the date picker.
● paddingLeft: set the padding from the left side of the date picker.
● paddingTop: set the padding from the top side of the date picker.
● paddingBottom: set the padding from the bottom side of the date picker.
● Padding: set the padding from the all side’s of the date picker.

Below code of padding attribute set the 40dp padding from all the side’s of the
date picker.

<DatePicker
android:id="@+id/simpleDatePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner"
android:padding="40dp"/> <!-- 40dp padding from all the sides of a date picker -->
Android DatePicker Example

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>

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()+"/"+ (picker.getMonth() +


1)+"/"+picker.getYear());

});

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.
Android TimePicker
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.

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:timePickerMode It is used to specify timepicker mode, either spinner or clock

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

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

Attributes of TimePicker:
Now let’s we discuss about the attributes that helps us to configure a time picker in
your xml file (layout).
1. id: id is an attribute used to uniquely identify a time picker.

<TimePicker
android:id="@+id/simpleTimePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/> <!-- id of a time picker -->

2. timePickerMode: time picker mode is an attribute of time picker used to set the
mode either spinner or clock. Default mode is clock but this mode is no longer used after
api level 21, so from api level 21 you have to set the mode to spinner.
Below we set the mode to spinner.

<TimePicker
android:id="@+id/simpleTimePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner" /> <!-- time picker mode of a time picker -->
3. background: background attribute is used to set the background of a time picker. We
can set a color or a drawable image in the background. We can also set the background
color programmatically means in java class.
Below we set the orange color for the background of a time picker.

<TimePicker
android:id="@+id/simpleTimePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner"
android:background="#F88F00" /> <!-- orange background color for the time picker
-->

Setting TimePicker Background In Java Class:


TimePicker simpleTimePicker=(TimePicker)findViewById(R.id.simpleTimePicker);
//initiate a time picker
simpleTimePicker.setBackgroundColor(Color.YELLOW); //Yellow background color for the
background of a time picker

4. padding: padding attribute is used to set the padding from left, right, top or bottom
for a time picker.

● paddingRight: set the padding from the right side of the time picker.
● paddingLeft: set the padding from the left side of the time picker.
● paddingTop: set the padding from the top side of the time picker.
● paddingBottom: set the padding from the bottom side of the time picker.
● Padding: set the padding from the all side’s of the time picker.

Below example we set the 20dp padding from all the side’s of the time picker.

<TimePicker
android:id="@+id/simpleTimePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner"
android:layout_centerHorizontal="true"
android:layout_marginTop="50dp"
android:padding="20dp"/> <!-- 20dp padding from all the sides of a time picker -->
Methods of TimePicker:

Let’s discuss some common methods of a time picker, which are used to configure
a time picker in our application.
1. setCurrentHour(Integer currentHour):
This method is used to set the current hours in a time picker.
setHour(Integer hour): setCurrentHour() method was deprecated in API level 23. From
api level 23 we have to use setHour(Integer hour). In this method there is only one
parameter of integer type which is used to set the value for hours.
Below we set the 5 value for the current hours.

TimePicker simpleTimePicker=(TimePicker)findViewById(R.id.simpleTimePicker); //
initiate a time picker
// set the value for current hours
simpleTimePicker.setCurrentHour(5); // before api level 23
simpleTimePicker.setHour(5); // from api level 23

2. setCurrentMinute(Integer currentMinute):
This method is used to set the current minutes in a time picker.
setMinute(Integer minute): setCurrentMinute() method was deprecated in API level 23.
From api level 23 we have to use setMinute(Integer minute). In this method there is only
one parameter of integer type which set the value for minutes.
Below we set the 35 value for the current minutes.

TimePicker simpleTimePicker=(TimePicker)findViewById(R.id.simpleTimePicker); //
initiate a time picker
// set the value for current hours
simpleTimePicker.setCurrentMinute(35); // before api level 23
simpleTimePicker.setMinute(35); // from api level 23

3. getCurrentHour():
This method is used to get the current hours from a time picker.
getCurrentHour(): getCurrentHour() method was deprecated in API level 23. From api
level 23 you have to use getHour(). This method returns an integer value.
Below we get the value of hours from a timepicker set by user.

TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker); //


initiate a time
pickerint hours =simpleTimePicker.getCurrentHour(); // before api level 23
int hours =simpleTimePicker.getHour(); // after api level 23

4. getCurrentMinute():
This method is used to get the current minutes from a time picker.
getMinute(): getCurrentMinute() method was deprecated in API level 23. From api level
23 we have to use getMinute(). This method returns an integer value.
Below we get the value of minutes from a time picker.

TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker); //


initiate a time picker
int minutes = simpleTimePicker.getCurrentMinute(); // before api level 23
int minutes = simpleTimePicker.getMinute(); // after api level 23

5. setIs24HourView(Boolean is24HourView):
This method is used to set the mode of the Time picker either 24 hour mode or AM/PM
mode. In this method we set a Boolean value either true or false. True value indicate 24
hour mode and false value indicate AM/PM mode.
Below we set the current mode of the time picker.

TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker); //


initiate a time picker
simpleTimePicker.setIs24HourView(true); // set 24 hours mode for the time picker

6. is24HourView():
This method is used to check the current mode of the time picker. This method returns
true if its 24 hour mode or false if AM/PM mode is set.
Below we get the current mode of the time picker:

TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker); //


initiate a time picker
Boolean mode=simpleTimePicker.is24HourView(); // check the current mode of the time
picker

7. setOnTimeChangedListener(TimePicker.OnTimeChangedListener
onTimeChangedListener):
This method is used to set the callback that indicates the time has been adjusted by the
user. onTimeChanged(TimePicker view, int hourOfDay, int minute) is an override function
of this listener in which we have three parameters first is for TimePicker, second for
getting hour of the day and last is for getting the minutes after changing the time of the
time picker.
Below we show the use of on time changed listener of a time picker.

TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker); //


initiate a time picker

simpleTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {

}
});

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"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.timepicker.MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button1"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="102dp"
android:layout_marginLeft="30dp"
android:layout_marginStart="30dp"
android:text="" />

<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:text="Change Time" />

<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginBottom="36dp" />
</RelativeLayout>

MainActivity.java
package example.javatpoint.com.timepicker;

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 {


TextView textview1;
TimePicker timepicker;
Button changetime;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

textview1=(TextView)findViewById(R.id.textView1);
timepicker=(TimePicker)findViewById(R.id.timePicker);
//Uncomment the below line of code for 24 hour view
timepicker.setIs24HourView(true);
changetime=(Button)findViewById(R.id.button1);

textview1.setText(getCurrentTime());

changetime.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
textview1.setText(getCurrentTime());
}
});

public String getCurrentTime(){


String currentTime="Current Time: "+timepicker.getCurrentHour()+":"+timepicker.getC
urrentMinute();
return currentTime;
}
}

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.

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.

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.

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

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 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 autocomplete


textview 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: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"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="example.javatpoint.com.autocompletetextview.MainActivity">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="What is your favourite programming language?"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.032" />

<AutoCompleteTextView
android:id="@+id/autoCompleteTextView"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_marginLeft="92dp"
android:layout_marginTop="144dp"
android:text=""
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

MainActivity.java
package example.javatpoint.com.autocompletetextview;

import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;

public class MainActivity extends AppCompatActivity {


String[] language ={"C","C++","Java",".NET","iPhone","Android","ASP.NET","PHP"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Creating the instance of ArrayAdapter containing list of language names
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.select_dialog_item,language);
//Getting the instance of AutoCompleteTextView
AutoCompleteTextView actv = (AutoCompleteTextView)findViewById(R.id.autoCompleteT
extView);
actv.setThreshold(1);//will start working from first character
actv.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
actv.setTextColor(Color.RED);
}
}
Output:

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.

You might also like