0% found this document useful (0 votes)
38 views142 pages

Chapter 4MAD

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

Chapter 4MAD

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 142

Chapter 4

Designing User Interface with View


Marks=12

Prepared By Prof Biradar R.Y.


Overview of UI
• Android apps will contain one or more activities and each
activity is a one screen of app.
• The activities will contain a multiple UI components.
• User interface is a collection of visual objects arranged on
the screen that the user can see and interact with.
• User interface can be created in java code or created in an
external XML layout file
• All user interface elements in an Android app are built
using View and ViewGroup objects.
• A View is an object that draws something on the screen
through which the user can interact. View is the SuperClass
of All component like TextView, EditText, ListView,
ViewGroup, etc
Overview of UI
• A ViewGroup is an object that holds other View
and ViewGroup objects in order to define the layout of
the interface. ViewGroup is the base class for Layouts.
• Heirarchy of View is shown in foll. Figure.
View Class

• A UI component is known as a view in Android.


• View is the basic building block of UI(User Interface) in
android.
• View is a base class for all UI components in android
like TextView, ImageView, Button etc.
• Every view occupies a rectangle shape. It can be an
image, a piece of text, a button or anything that an
android application can display.
• A View is also known as Widget in Android. Any
visual(that we can see on screen) and interactive(with
which user can interact with) is called a Widget.
View Class
• Subclasses View
– TextView
– EditText
– Button
– CheckBox
– RadioButton
– ImageButton
– Progress Bar
– Spinner
1. TextView
• View is the parent class of TextView.
• used to set and display text to the user
• It also allows user to optionally edit it, the
basic class does not allow editing.
• So TextView control will act as like label
control.
• TextView is represented by the Android
class android.widget.TextView
TextView
Creation of TextView
• TextView code in XML:
<TextView
android:id="@+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=“Hello Android" />
• TextView code in JAVA:
TextView textView = findViewById(R.id.tv1);
tv1.setText(“Android"); //set text for text view
TextView
Attributes or Properties of TextView
android:layout_width="wrap_content" and
android:layout_height="wrap_content" are compulsory to write
for every view, because we must define the width and height
for every view that we create.
Sr Attribute
No.
1. android:id: id is an attribute used to uniquely identify a text
view. This can be retrieved using findViewById() method.
Ex: android:id="@+id/textView1”
2. android:gravity: The gravity attribute is an optional attribute
which is used to control the alignment of the text like left,
right, center, top, bottom, center_vertical, center_horizontal
etc. Ex: android:gravity="center_horizontal”
TextView
Sr Attribute
No.
3. android:text: text attribute is used to set the text in a text
view. We can set the text in xml as well as in the java class.
Ex: android:text=“Hello World“
4. android:textColor: textColor attribute is used to set the text
color of a text view. Color value is in the form of “#argb”,
“#rgb”, “#rrggbb”, or “#aarrggbb”.
Ex: android:textColor="#f00”
5. android:textSize: textSize attribute is used to set the size of
text of a text view. We can set the text size in sp(scalable pixel)
or dp(density pixel). Ex: android:textSize=“30sp”
6. android:textStyle: textStyle attribute is used to set the text
style of a text view. Text styles are bold, italic and normal. If
we need to use two or more styles for a text view then “|”
operator is used . Ex: android:textStyle=“bold|italic”
TextView
Sr Attribute
No.
7. android:background: background attribute is used to set the
background of a text view. We can set a color or image in the
background of a text view. Ex: android:background=“#00b“
8. android:padding: padding attribute is used to set the padding
from left, right, top or bottom that is padding from all the
side’s of text view. Ex: android:padding=“10dp
9. android:capitalize: specifies that this TextView has a textual
input method and should automatically capitalize what the
user types. The default is "none". Must be one of the
following constant values.
Don't automatically capitalize anything - 0
Capitalize the first word of each sentence - 1
Capitalize the first letter of every word - 2
Capitalize every character - 3
TextView
Sr Attribute
No.
10 android:cursorVisible: Makes the cursor visible (the default)
. or invisible. May be a boolean value, such as "true" or "false“.
Ex: android:cursorVisible=“true”
11 android:ems: Makes the TextView be exactly this many ems
wide. Ex: android:ems=“10”
12 android:fontFamily: Font family (named by string) for the text.
13 android:hint:Hint text to display when the text is empty.
Ex: android:hint=“Search”
14 android:password :Whether the characters of the field are
displayed as password dots instead of themselves. Possible
value either "true" or "false“. Ex: android:password=“true”
15 android:inputType :The type of data being placed in a text
field. Phone, Date, Time, Number, Password etc.
Ex: android:inputType="textPassword"
TextView
Sr Attribute
No.
16 android:textAllCaps: Present the text in ALL CAPS. Possible
value either "true" or "false". Ex: android:textAllCaps=”true”
17 android:textIsSelectable:Indicates that the content of a non-
editable text can be selected. Possible value either "true" or
"false“. Ex: android:textIsSelectable=”true”
18 android:textColorHighlight Color of the text selection
highlight. Ex: android:textColorHighlight=“#0F0”
Example of TextView
Contents of activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="Hello"
android:textColor="#F00"
android:background="#00F"
/>
</RelativeLayout>
Contents of MainActivity.java
package com.example.demoapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends Activity


{
TextView tv;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

tv= findViewById(R.id.textview1);
}
}
2. EditText
• It provide an input or text field where user can enter
something like his name details, phone number etc.
• EditText is a subclass of TextView with text editing
operations
• It is like a TextField control.
• EditText is represented by the Android
class android.widget.EditText.
EditText
Creation of EditText
• EditText code in XML:
<EditText android:id="@+id/editText1"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
• EditText code in JAVA:
EditText editText1 = findViewById(R.id.editText1);
EditText
Attributes or Properties of EditText
Sr Attribute
No.
1. android:id: id is an attribute used to uniquely identify a edit
text This can be retrieved using findViewById() method.
Ex: android:id="@+id/edittext1”
2. android:gravity: The gravity attribute is an optional attribute
which is used to control the alignment of the text like left,
right, center, top, bottom, center_vertical, center_horizontal
etc. Ex: android:gravity="center_horizontal”
3 android:autoText: If set, specifies that this EditText has a
textual input method and automatically corrects some
common spelling errors.
4 android:text This is the Text to display.
EditText

Sr Attribute
No.
5 android:drawableBottom :This is the drawable to be drawn
below the text.
6. android:drawableRight :This is the drawable to be drawn to
the right of the text.
7. android:editable:If set, specifies that this EditView has an
input method.
8 android:background: background attribute is used to set the
background of a edit view. We can set a color or image in the
background of a edit view. Ex: android:background=“#00b“
9 android:onClick :This is the name of the method in this View's
context to invoke when the view is clicked.
10 android:visibility: This controls the initial visibility of the view.
It may take one of the 3 values: visible,invisible,gone.
Example of EditText
Contents of activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">

<EditText
android:id="@+id/editText1"
android:layout_marginTop="100dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint="Enter Name" />

</RelativeLayout>
Contents of MainActivity.java
package com.example.demoapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;

public class MainActivity extends Activity


{
EditText etName;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

etName= findViewById(R.id.editText1);
}
}
3. AutoCompleteTextView
• AutoCompleteTextView is an type of edit text.
• It gives suggestions to the user if the user types
something in the AutoCompleteTextView. The
suggestions list is shown in a drop down menu from
which a user can select the desired item.
• The list of suggestions is obtained from an adapter and
it appears only after a number of characters that are
specified in the threshold.
• It is subclass of EditText class
• AutoCompleteTextView is represented by the Android
class android.widget.AutoCompleteTextView.
AutoCompleteTextView
Creation of AutoCompleteTextView
• AutoCompleteTextView code in XML:
< AutoCompleteTextView android:id="@+id/autotv"
android:layout_height="wrap_content"
android:layout_width="match_parent“/>
• AutoCompleteTextView code in JAVA:
AutoCompleteTextView actv= findViewById(R.id.autotv);
AutoCompleteTextView
 Attributes or Properties of AutoCompleteTextView
Sr Attribute
No.
1. android:id: id is an attribute used to uniquely identify a auto
complete text view. This can be retrieved using findViewById()
method. Ex: android:id="@+id/autotv”
2. android:completionThreshold :This defines the number of
characters that the user must type before completion
suggestions are displayed in a drop down menu.
3 android:completionHint :This defines the hint displayed in the
drop down menu.
4 android:dropDownAnchor: This is the View to anchor the
auto-complete dropdown to.
 Attributes or Properties of AutoCompleteTextView
Sr Attribute
No.
5. android:dropDownHeight:This specifies the basic height of
the dropdown.
6. android:dropDownWidth :This specifies the basic width of the
dropdown.
7 android:popupBackground :This sets the background.
8 android:dropDownHorizontalOffset Amount of pixels by
which the drop down should be offset horizontally.
9 android:dropDownVerticalOffset Amount of pixels by which
the drop down should be offset vertically
Example of AutoCompleteTextView
Contents of activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">

<AutoCompleteTextView
android:id="@+id/autotv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_centerInParent="true"
android:hint="Search"/>
Contents of MainActivity.java
package com.example.demoapp;

import android.app.Activity;
import android.os.Bundle;
import android.widget.*;

public class MainActivity extends Activity


{
AutoCompleteTextView actv;
String branches[]={"Agricultre","Automobile Engg","Architectre","Biotechnology","Civil
Engg","Computer Engg","Chemical Engg","Electrical Engg","Electronics & Telecommunication
Engg","Mehanical Engg"};
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

actv=(AutoCompleteTextView) findViewById(R.id.autotv);

ArrayAdapter<String> adapter=new
ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,branches);
actv.setAdapter(adapter);
actv.setThreshold(1);

}
4. Button
• A Button is a Push-button. Button can be pressed, or
clicked, by the user to perform an action.
• There are different types of buttons used in android such
as CompoundButton, ToggleButton, RadioButton.
• Button is a subclass of TextView class .
• Button may contain text and images. To add both image
and text in android button, use button
property android:drawableTop, android:drawableBottom,
android:drawableLeft or android:drawableRight.
• Buttons with images on are also called ImageButton.
• Button is represented by the Android
class android.widget.Button.
Button
Creation of Button
• Button code in XML:
<Button
android:id="@+id/btsubmit"
android:layout_height="wrap_content“
android:layout_width="match_parent“
android:text=“Submit”/>

• Button code in JAVA:


Button b1= findViewById(R.id.btsubmit);
 Attributes or Properties of Button
Sr Attribute
No.
1. android:id: id is an attribute used to uniquely identify a button.
This can be retrieved using findViewById() method.
Ex: android:id="@+id/button”
2. android:text: text attribute is used to set the text in a Button
3 android:drawableBottom :This is the drawable to be drawn
below the text. Ex:android:drawableBottom="@drawable/img1”
4 android:drawableRight:This is the drawable to be drawn to the
right of the text. Ex:android:drawableRight="@drawable/img1”
5 android:drawableLeft:This is the drawable to be drawn to the
left of the text. Ex:android:drawableLeft="@drawable/img1”
6 android:drawableTop:This is the drawable to be drawn to the
top of the text. Ex:android:drawableTop="@drawable/img1”
Sr Attribute
No.
7 android:background: background attribute is used to set the
background. We can set a color or image in the background of
a Button. Ex: android:background=“#00b“
Ex: android:background="@drawable/img1 “
8 android:onClick :This is the name of the method in this View's
context to invoke when the view is clicked.
9. android:visibility :This controls the initial visibility of the view.
It may take one of the 3 values: visible,invisible,gone.
Button
Handling Events on Button
• There are 2 ways to handle the click event in button
1. Onclick in xml layout
2. Using an OnClickListener
1. Onclick in xml layout
• When the user clicks a button, the Button object receives an
on-click event.
• To define the click event handler for a button, add
the android:onClick attribute to the <Button> tag in XML
layout file.
• The value for this attribute must be the name of the method
we want to call in response to a click event.
• When users tap the views which hold android:onClick ,
android looks for the method in the activity. If the exact
method found, that will start execution.
• onClick attribute in XML file is as follows
2. Using an OnClickListener
• The OnClickListener() interface has an onClick(View v) method
that is called when the view (component) is clicked.
• the listener is set using the setOnClickListener() method.
• Most of the GUI Android components can be bundled with
an OnClickListener.
For example:
// Get button using its ID:
Button btn = findViewById(R.id.my_btn);

// Set OnCLickListener() using anonymous class:


button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{ // Code here executes after user presses button
}
});
Example of Button using onClick attribute
Contents of activity_main.xml file <Button
<?xml version="1.0" encoding="utf-8"?>
android:id="@+id/button1"
<RelativeLayout android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/ android:layout_height="wrap_content"
apk/res/android" android:layout_below="@+id/editText1“
android:layout_height="match_parent" android:layout_centerHorizontal="true"
android:layout_width="match_parent"> android:layout_marginTop="82dp“
android:onClick=“submit”
<EditText android:text=“Submit" />
android:id="@+id/editText1"
android:layout_width="wrap_content" <TextView
android:layout_height="wrap_content" android:id="@+id/textView1"
android:layout_alignParentTop="true" android:layout_width="wrap_content"
android:layout_centerHorizontal="true" android:layout_height="wrap_content"
android:layout_marginTop="56dp" android:layout_below="@+id/button1"
android:ems="10“/ > android:layout_centerHorizontal="true"
android:layout_marginTop="76dp"
android:text="TextView" />

</RelativeLayout>
using onClick attribute
Contents of MainActivity.java
package com.example.sampleapp; etName=findViewById(R.id.editText1);
tvresult=findViewById(R.id.textView1);
import android.app.Activity;
}
import android.os.Bundle;
public void submit(View V)
import android.view.View;
{
import android.widget.EditText;
String s=etName.getText().toString();
import android.widget.TextView;
tvresult.setText("Welcome "+s);
}
public class MainActivity extends Activity
}
{
EditText etName;
TextView tvresult;

@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Example of Button using OnClickListener
Contents of activity_main.xml file <Button
<?xml version="1.0" encoding="utf-8"?>
android:id="@+id/button1"
<RelativeLayout android:layout_width="wrap_content"
xmlns:android="http://schemas.android.com/ android:layout_height="wrap_content"
apk/res/android" android:layout_below="@+id/editText1“
android:layout_height="match_parent" android:layout_centerHorizontal="true"
android:layout_width="match_parent"> android:layout_marginTop="82dp“
android:text=“Submit" />
<EditText
android:id="@+id/editText1" <TextView
android:layout_width="wrap_content" android:id="@+id/textView1"
android:layout_height="wrap_content" android:layout_width="wrap_content"
android:layout_alignParentTop="true" android:layout_height="wrap_content"
android:layout_centerHorizontal="true" android:layout_below="@+id/button1"
android:layout_marginTop="56dp" android:layout_centerHorizontal="true"
android:ems="10“/ > android:layout_marginTop="76dp"
android:text="TextView" />

</RelativeLayout>
using OnClickListener
Contents of MainActivity.java
package com.example.sampleapp; etName=findViewById(R.id.editText1);
tvresult=findViewById(R.id.textView1);
import android.app.Activity;
bt=findViewById(R.id.button1);
import android.os.Bundle;
bt.setOnClickListener(new
import android.view.View;
View.OnClickListener() {
import android.widget.EditText;
public void onClick(View v)
import android.widget.TextView;
{
Import android.widget.Button;
String s=etName.getText().toString();
tvresult.setText("Welcome "+s);
public class MainActivity extends Activity }
{ });
EditText etName; }
TextView tvresult;
Button bt; }
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
5. ImageButton
• ImageButton is a button with an image that can be
pressed or clicked by the users.
• ImageButton is represented by the Android
class android.widget.ImageButton.
• has all the properties of a normal button
• We can add a image to the button by using
attribute android:src of <ImageButton> in XML
layout file and within java class by using
setImageResource() method.
ImageButton
Creation of ImageButton
• ImageButton code in XML:
<ImageButton
android:id="@+id/btsubmit"
android:layout_height="wrap_content“
android:layout_width="match_parent“
android:src="@drawable/submit_icon”/>

• ImageButton code in JAVA:


ImageButton b1=findViewById(R.id.btsubmit);
 Attributes or Properties of ImageButton
Sr Attribute
No.
1 android:id: id is an attribute used to uniquely identify a button. This can be
retrieved using findViewById() method. Ex: android:id="@+id/imgbt”

2 android:background: background attribute is used to set the background.


We can set a color or image in the background of a ImageButton. Ex:
android:background=“#00b“

3 android:padding: padding attribute is used to set the padding from left, right,
top or bottom of the ImageButton.
paddingRight : set the padding from the right side of the image button.
paddingLeft : set the padding from the left side of the image button.
paddingTop : set the padding from the top side of the image button.
paddingBottom : set the padding from the bottom side of the image button.
padding : set the padding from the all side’s of the image button.
4 android:src: used to set a source file of image.
Ex: android:src="@drawable/home"

5 android:onClick :This is the name of the method in this View's context to


invoke when the view is clicked.
Sr Attribute
No.
6 android:visibility :This controls the initial visibility of the view. It may take
one of the 3 values: visible,invisible,gone.

 Handling Events on ImageButton


• There are 2 ways to handle the click event
1. Onclick in xml layout
2. Using an OnClickListener
1. Onclick in xml layout
When the user clicks an imagebutton, the ImageButton object
receives an on-click event.
To define the click event handler for an imagebutton, add
the android:onClick attribute to the <ImageButton> tag in
XML layout file. The value for this attribute must be the name
of the method we want to call in response to a click event.
ImageButton
• onClick attribute in XML file is as follows
<ImageButton
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content“
android:onClick="submit"
android:src=“@drawable/Submit" />
• In MainActivity class
public void submit(View view)
{
// Do something in response to Imagebutton click
}
ImageButton
2. Using an OnClickListener
To specify an action when the imagebutton is pressed, set a
OnClickListener on the button object using setOnClickListener()
method
For exmaple:
imgbt.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{ // Code here executes after user presses imagebutton
}
});
Example of ImageButton using OnClickListener
Contents of activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ImageButton
android:id="@+id/imgBt1"
android:layout_width="131dp"
android:layout_height="50dp"
android:src="@drawable/submit"
android:layout_centerInParent="true“ />

</RelativeLayout>
Contents of MainActivity.java
package com.example.sampleapp; bt.setOnClickListener(new
View.OnClickListener() {
import android.app.Activity; public void onClick(View v)
import android.os.Bundle; {
import android.view.View; Toast.makeText(getApplicationContext(),"This is
Import android.widget.ImageButton; ImageButton",Toast.LENGTH_LONG).show();
}
public class MainActivity extends Activity });
{ }
ImageButton bt;
@Override }
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt= findViewById(R.id.bton1);
6. ToggleButton
• Used to display ON (Checked) or OFF (Unchecked) states as
a button with a light indicator.
• useful for the users to change the settings between two
states either ON or OFF.
• example of ToggleButton is doing on/off in sound,
Bluetooth, wifi, hotspot etc.
• ToggleButton belongs to android.widget.ToggleButton class.
• It is a subclass of CompoundButton.
• By default, ToggleButton will be in OFF (Unchecked) state.
We can change the state of ToggleButton by using
android:checked attribute.
• For ex: android:checked = “true”
• From Android 4.0 Switch control
can be used
ToggleButton
Creation of ToggleButton
• ToggleButton code in XML:
<ToggleButton
android:id="@+id/tb1"
android:layout_height="wrap_content“
android:layout_width=“wrap_content“
android:checked="true"
android:drawableLeft="@drawable/bluetooth"
android:textOff="OFF"
android:textOn="ON“ />
• ToggleButton code in JAVA:
ToggleButton b1=findViewById(R.id.tb1);
ToggleButton
 Attributes or Properties of ToggleButton
Sr Attribute
No.
1 android:id: id is an attribute used to uniquely identify a togglebutton. This
can be retrieved using findViewById() method. Ex: android:id="@+id/tb”
2 android:onClick :This is the name of the method in this View's context to
invoke when the view is clicked.
3 android:textOff This is the text for the togglebutton when it is not
checked.
4 android:textOn This is the text for the togglebutton when it is checked.

5 android:checked: takes boolean value and represents the initial state of


the toggle button
6 android:background: background attribute is used to set the background
of a text view. We can set a color or image in the background of a text
view. Ex: android:background=“#00b“
7 android:gravity:It is used to specify how to align the text like left, right, center,
top, bottom, center_vertical, center_horizontal etc.
 Attributes or Properties of ToggleButton
Sr Attribute
No.
8 android:text: text attribute is used to set the text in a TogggleButton

9 android:drawableBottom :This is the drawable to be drawn below the


text. Ex:android:drawableBottom="@drawable/ic_launcher”
10 android:drawableRight:This is the drawable to be drawn to the right of
the text. Ex:android:drawableRight="@drawable/ic_launcher”
11 android:drawableLeft:This is the drawable to be drawn to the left of the
text. Ex: android:drawableLeft="@drawable/ic_launcher”
12 android:drawableTopThis is the drawable to be drawn to the top of the
text. Ex: android:drawableTop="@drawable/ic_launcher”
13 android:visibility :This controls the initial visibility of the view. It may take
one of the 3 values: visible,invisible,gone.
ToggleButton
 Handling Events on ToggleButton
1. Using onClick attribute in XML
2. Using OnClickListener
3. Using OnCheckedChangeListener
ToggleButton
Using an OnClickListener
To specify an action when the togglebutton is pressed, set a
OnClickListener on the togglebutton object using
setOnClickListener() method
For exmaple:
tb.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{ if(tb.isChecked())
//to do something
else
//to do something
}
});
Using an OnCheckedChangeListener
To specify an action when the togglebutton is pressed, set a
OnCheckedChangeListener on the togglebutton object using
setOnCheckedChangeListener () method
For exmaple:
tb.setOnCheckedChangeListener (new
CompoundButton.OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked)
{ if(isChecked)
//to do something
else
//to do something
}
});
Example of ToggleButton using OnClickListener
Contents of activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ToggleButton
android:id="@+id/tb1"
android:layout_width="96dp"
android:layout_height="40dp"
android:layout_marginLeft="160dp"
android:layout_marginTop="130dp"
android:checked="true“
android:textOff="OFF"
android:textOn="ON“/>

</RelativeLayout>
Contents of MainActivity.java
package com.example.sampleapp; tb.setOnClickListener(new
View.OnClickListener() {
import android.app.Activity;
public void onClick(View v)
{
import android.os.Bundle;
if(tb.isChecked())
import android.view.View; Toast.makeText(getApplicationContext(),
Import android.widget.ToggleButton; “Toggle On", Toast.LENGTH_SHORT).show();
import android.widget.Toast; else
Toast.makeText(getApplicationContext(),
public class MainActivity extends Activity “Toggle Off", Toast.LENGTH_SHORT).show(); }
{ });
ToggleButton tb; }
@Override
protected void onCreate(Bundle savedInstanceState) }
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tb=(ToggleButton) findViewById(R.id.tb1);
Example of ToggleButton using
OnCheckedChangeListener
Contents of activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ToggleButton
android:id="@+id/tb1"
android:layout_width="96dp"
android:layout_height="40dp"
android:layout_marginLeft="160dp"
android:layout_marginTop="130dp"
android:checked="true“
android:textOff="OFF"
android:textOn="ON“/> </RelativeLayout>
Example of ToggleButton using OnCheckedChangeListener
Contents of MainActivity.java
tb.setOnCheckedChangeListener(new
package com.example.sampleapp;
CompoundButton.OnCheckedChangeListe
ner()
import android.app.Activity;
{
import android.os.Bundle;
@Override
import android.view.View;
public void
Import android.widget.ToggleButton;
onCheckedChanged(CompoundButton
import android.widget.CompoundButton; buttonView, boolean isChecked)
import android.widget.Toast; {
if(isChecked)
public class MainActivity extends Activity Toast.makeText(getApplicationContext(),
{ “Toggle On", Toast.LENGTH_SHORT).show();
ToggleButton tb;
@Override else
Toast.makeText(getApplicationContext(),
protected void onCreate(Bundle savedInstanceState)
“Toggle Off", Toast.LENGTH_SHORT).show(); }
{
});
super.onCreate(savedInstanceState);
}
setContentView(R.layout.activity_main);
tb=(ToggleButton) findViewById(R.id.tb1);
}
7. RadioButton
• Radio buttons allow the user to select only one option to
select from the group of options
• A radio button consists of two states – checked and
unchecked. Clicking an unchecked button changes its state to
“checked” state and “unchecked” for the previously selected
radio button.
• Radio buttons are used with 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.
• RadioButton belongs to android.widget.RadioButton class.
• It is subclass of CompoundButton.
• We can change the default state of RadioButton by
using android:checked attribute.
RadioButton
RadioButton
 Attributes or Properties of RadioButton
Sr Attribute
No.
1 android:id: id is an attribute used to uniquely identify a radiobutton. This
can be retrieved using findViewById() method. Ex: android:id="@+id/rb”
2 android:onClick :This is the name of the method in this View's context to
invoke when the view is clicked.
3 android:textOff This is the text for the radiobutton when it is not checked.

4 android:textOn This is the text for the radiobutton when it is checked.

5 android:checked: takes boolean value and represents the initial state of


the radio button
6 android:background: background attribute is used to set the background
of a radiobutton. We can set a color or image in the background of a text
view. Ex: android:background=“#00b“
7 android:visibility :This controls the initial visibility of the view. It may take
one of the 3 values: visible,invisible,gone.
RadioButton
 Attributes or Properties of RadioButton
Sr Attribute
No.

8 android:text: text attribute is used to set the text in a RadioButton

9 android:drawableBottom :This is the drawable to be drawn below the


text. Ex:android:drawableBottom="@drawable/ic_launcher”

10 android:drawableRight:This is the drawable to be drawn to the right of


the text. Ex:android:drawableRight="@drawable/ic_launcher”

11 android:drawableLeft:This is the drawable to be drawn to the left of the


text. Ex: android:drawableLeft="@drawable/ic_launcher”

12 android:drawableTop: This is the drawable to be drawn to the top of the


text. Ex: android:drawableTop="@drawable/ic_launcher”
Attribute
13 android:layoutDirection : By Default RadioButton Will be in Left to Right
Direction , If you want to change use android:layoutDirection="rtl"

 Attributes or Properties of RadioGroup


1 android:orientation : This property on the Radio group defines the
orientation to position its child view consisting of Radio Buttons. It can be
either horizontal or vertical. Default is Vertical Orientaion.
RadioButton
Creation of RadioButton
• RadioButton code in XML:
<RadioGroup android:id="@+id/rg1”
android:layout_width="wrap_content"
android:layout_height="wrap_content“
android:orientation="vertical" >

<RadioButton android:id="@+id/rb1”
android:layout_width="wrap_content"
android:layout_height="wrap_content“
android:text=“Male“/>

<RadioButton android:id="@+id/rb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content“
android:text=“Female" />
</RadioGroup>
RadioButton
Creation of RadioButton
• RadioButton code in Java:
RadioButton b1=findViewById(R.id.rb1);

Handling Events on RadioButton


• There are 3 ways to handle the click event
1. Using onClick attribute in XML
2. Using OnClickListener
3. Using OnCheckedChangeListener
Example of RadioButton using
OnCheckedChangeListener
Contents of activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"> <RadioButton
<RadioGroup android:id="@+id/rbfemale"
android:id="@+id/rg" android:layout_width="wrap_content"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_height="wrap_content" android:text="Female" />
</RadioGroup>
android:layout_marginLeft="160dp"
android:layout_marginTop="100dp" <TextView
android:orientation="horizontal"> android:id="@+id/tv"
android:layout_width="wrap_content"
<RadioButton android:layout_height="wrap_content"
android:id="@+id/rbmale" android:layout_marginLeft="70dp"
android:layout_width="wrap_content" android:layout_marginTop="150dp"
android:layout_height="wrap_content" android:text="TextView" />
android:text="Male" /> </RelativeLayout>
Example of RadioButton using
OnCheckedChangeListener
Contents of MainActivity.java
package com.example.sampleapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

public class MainActivity extends Activity


{
RadioButton rb1,rb2;
RadioGroup rg;
TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rb1=(RadioButton) findViewById(R.id.rbmale);
Example of RadioButton using
OnCheckedChangeListener
rb2=(RadioButton) findViewById(R.id.rbfemale);
tv=(TextView) findViewById(R.id.tv);
rg=(RadioGroup) findViewById(R.id.rg);

rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(RadioGroup group, int checkId)
{
switch(checkId)
{
case R.id.rbmale: tv.setText("Male is selected");
break;
case R.id.rbfemale: tv.setText("Female is selected");
break;
}
}
});
}
}
8. CheckBox
• It has two states –checked or unchecked.
• Checkboxes allow the user to select one or more
options from a set. For example, selecting hobbies.
• CheckBox belongs to android.widget.CheckBox class.
• It is subclass of CompoundButton.
• We can change the default state of CheckBox by
using android:checked attribute.
CheckBox
 Attributes or Properties of CheckBox
Sr Attribute
No.
1 android:id: id is an attribute used to uniquely identify a checkbox. This can
be retrieved using findViewById() method. Ex: android:id="@+id/cb”
2 android:onClick :This is the name of the method in this View's context to
invoke when the view is clicked.
3 android:checked: takes boolean value and represents the initial state of
the toggle button
4 android:background: background attribute is used to set the background
of a text view. We can set a color or image in the background of a text
view. Ex: android:background=“#00b“
5 android:gravity:It is used to specify how to align the text like left, right, center,
top, etc.
CheckBox
 Attributes or Properties of CheckBox
Sr Attribute
No.
6 android:text: text attribute is used to set the text in a checkbox

7 android:drawableBottom :This is the drawable to be drawn below the


text. Ex:android:drawableBottom="@drawable/ic_launcher”
8 android:drawableRight:This is the drawable to be drawn to the right of
the text. Ex:android:drawableRight="@drawable/ic_launcher”
9 android:drawableLeft:This is the drawable to be drawn to the left of the
text. Ex: android:drawableLeft="@drawable/ic_launcher”
10 android:drawableTopThis is the drawable to be drawn to the top of the
text. Ex: android:drawableTop="@drawable/ic_launcher”
11 android:visibility :This controls the initial visibility of the view. It may take
one of the 3 values: visible,invisible,gone.
CheckBox
Creation of CheckBox
• CheckBox code in 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">
<CheckBox
android:id="@+id/chk1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:checked="true"
android:text="Java" /> </RelativeLayout>
CheckBox
Creation of CheckBox
• CheckBox code in Java:
CheckBox cb1=(CheckBox) findViewById(R.id.chk1);

Handling Events on CheckBox


• There are 3 ways to handle the click event
1. Using onClick attribute in XML
2. Using OnClickListener
3. Using OnCheckedChangeListener
Example of CheckBox using OnClickListener
Contents of activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<CheckBox
android:id="@+id/chk1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" <TextView
android:layout_marginTop="200dp" android:id="@+id/tv"
android:layout_marginLeft="70dp" android:layout_width="wrap_content"
android:text="Java"/> android:layout_height="wrap_content"
android:layout_marginLeft="70dp"
<CheckBox android:layout_marginTop="150dp"
android:id="@+id/chk2" android:text="TextView" />
android:layout_width="wrap_content"
android:layout_height="wrap_content" </RelativeLayout>
android:layout_marginTop="220dp"
android:layout_marginLeft="70dp"
android:text="Android"/>
Example of CheckBox using OnClickListener
Contents of MainActivity.java cb1=findViewById(R.id.chk1);
package com.example.sampleapp; cb2=findViewById(R.id.chk2);
import android.app.Activity; tvres=findViewById(R.id.tv);
import android.os.Bundle;
import android.view.View; cb1.setOnClickListener(this);
import android.widget.CheckBox cb2.setOnClickListener(this);
import android.widget.TextView;
import android.view.View.OnClickListener;
}
public void onClick(View v)
public class MainActivity extends Activity implements {
View.OnClickListener str="";
{ if(cb1.isChecked())
TextView tvres; str+="Java is selected";
CheckBox cb1,cb2; if(cb2.isChecked())
str+="Android is selected";
String str="";
tv.setText(str);
@Override }
protected void onCreate(Bundle savedInstanceState)
{ super.onCreate(savedInstanceState); }
setContentView(R.layout.activity_main);
9. ProgressBar
• Progress bars are used to show progress of a task
graphically.
• Progress bar supports two modes :
1. determinate(Horizontal) ,
2. and indeterminate( Circular or Spinning wheel)
• Represented by “android.widget.ProgressBar” class
• By default, a progress bar is a spinning wheel
• Indeterminate mode is used in application when we don’t
know the amount of work to be done.
• Determinate mode is used in application when you want to
show that a specific quantity of progress has occurred. For
example, the percent remaining of a file being retrieved,
• To change to a horizontal progress bar, apply the horizontal
style.
 Creation of ProgressBar
• Indeterminate Progress (Circular ProgressBar)
<ProgressBar
android:id="@+id/indeterminateBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

• Determinate Progress (Horizontal ProgressBar)


<ProgressBar
android:id="@+id/determinateBar"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:progress="25"/>
ProgressBar
• progress bar styles provided by the system include:
1. Widget.ProgressBar.Horizontal
2. Widget.ProgressBar.Small
3. Widget.ProgressBar.Large
4. Widget.ProgressBar.Inverse
5. Widget.ProgressBar.Small.Inverse
6. Widget.ProgressBar.Large.Inverse

• setProgress(int) method is used to update the percentage of


progress
• incrementProgressBy(int) is used to increase the current
progress completed by a specified amount.
ProgressBar
 Attributes or Properties of ProgressBar
Sr Attribute
No.

1 android:id: id is an attribute used to uniquely identify


a progressbar. This can be retrieved using findViewById()
method. Ex: android:id="@+id/pb”
2 android:max: used to define maximum value of the progress .
It must be an integer value like 100, 200 etc.
3 android:progress: used to define the default progress value
between 0 and max. It must be an integer value.
4 android:background: background attribute is used to set the
background of a text view. We can set a color or image in the
background of a text view. Ex: android:background=“#00b“

5 android:progressDrawable: used to set the custom drawable


for the progress mode.
ProgressBar
 Attributes or Properties of ProgressBar
Sr Attribute
No.

6 Style: By default the progress bar will be displayed as a


spinning wheel. If we want it to be displayed as a horizontal
bar, we need to set the attribute as
style="@android:style/Widget.ProgressBar.Horizontal"
7 android:indeterminate: used to enable the indeterminate
mode. Progress bar shows a cyclic animation without an
indication of progress. Takes boolean value.
Example of ProgressBar
Contents of activity_main.xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<ProgressBar
android:id="@+id/progress"
style="@style/Widget.AppCompat.ProgressBar.Horizontal"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_centerHorizontal="true"
android:max="100"
android:progress="0" />

<Button
android:id="@+id/bt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginLeft="100dp"
android:layout_marginTop="200dp"
android:text="Start" /> </RelativeLayout>
Example of ProgressBar
Contents of MainActivity.java file
package com.example.progressdemo;
import androidx.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;

public class MainActivity extends Activity {


ProgressBar pb;
Button b;
int progress=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

pb = findViewById(R.id.progress);
b = findViewById(R.id.bt);
Example of ProgressBar
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
setProgressValue(progress);
} });
}
void setProgressValue(final int progress) {
pb.setProgress(progress);
Thread thread = new Thread() {
@Override
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) { }
setProgressValue(progress+10);
} };
thread.start();
}
}
ListView
• ListView is a view which groups several items and display
them in vertical scrollable list.
• list items are automatically inserted to the list using
an Adapter that pulls data from a source such as an array
or database.
• ListView subclasses is of AdapterView .
• List View is by default scrollable.
• A list view does not know the details, such as type and
contents.
• list view requests views on demand from a Adapter as
needed, such as to display new views as the user scrolls up
or down.
• Adapter will act as an intermediate between the data
sources and adapter views such as ListView
• Types of adapters
ArrayAdapter It will expects an Array or List as input.
CursorAdapter 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

• to display items in the list, we need to


call

setAdapter(adapter)
ListView
 Attributes or Properties of ListView
Sr Attribute
No.

1 android:id: id is an attribute used to uniquely identify a


listview. This can be retrieved using findViewById() method. Ex:
android:id="@+id/list”
2 android:entries: Reference to an array resource that will
populate the ListView.
3 android:footerDividersEnabled: It has two values: true or
false. By default, it’s true, but when set to false, the ListView
won’t draw any divider before each footer.
4 android:headersDividersEnabled: It has two values: true or
false. By default, it’s true, but when set to false, the ListView
won’t draw any divider after each header.
ListView
Sr Attribute
No.
5 android:divider: This is drawable or color to draw between list
items.
6 android: dividerHeight: This specifies height of the divider.
This could be in px, dp, sp, in, or mm.
7 android: listSelector: This specifies color of selected item

8 android:choiceMode: used to specify the number of items


that can be selected at once from the list.
 Creation of ListView
• In XML file
<ListView
android:id="@+id/mobile_list"
android:layout_width="match_parent"
android:layout_height="wrap_content" > </ListView>

• In Java File
ListView listView = findViewById(R.id.mobile_list);
listView.setAdapter(adapter);
ArrayAdapter
• Adapter will act as an intermediate between the data
sources and adapter views.
• Adapter can be used to supply the data to like spinner, list
view, grid view etc.
• ArrayAdapter is useful when list contains single type of
items which stored in an array. For ex, list of phone
contacts, countries or names.
• Creation of ArrayAdapter
ArrayAdapter(Context context, int resource,Type[] objects)
1. context means the reference of current class( this keyword),
getApplicationContext() can also be used.
2. resource id used to set the layout(xml file) for list items in which
we have a text view.
3. array of objects, used to set the array of elements in the textView.
 ArrayAdapter
• Ex:
ArrayAdapter<String> adapter = new
ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
Example of ListView
Contents of activity_main.xml file
<?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/animal"
android:layout_width="match_parent"
android:layout_height="wrap_content“
android:divider="#000“
android:dividerHeight="2dp“/ >

</LinearLayout>
Example of ListView
Contents of MainActivity.java file
package com.example.listdemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {


ListView lst;
String[] animals = {"Lion","Tiger","Monkey","Elephant","Dog","Cat","Camel"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lst = (ListView) findViewById(R.id.animal);
ArrayAdapter<String> adapter=new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,animals);
lst.setAdapter(adapter);
}
}
GridView
• GridView shows items in two-dimensional scrolling
grid (rows & columns)
• The items in the grid come from
the ListAdapter associated with this view.
• GridView is subclasses of AdapterView
• GridView is default scrollable
• Adapter is used to fill data in gridview:
• Ex: In Gallery, number of images displayed using grid.
GridView
 Creation of GridView:
• GridView code in XML:
<GridView
android:id="@+id/gridview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:numColumns="3"/>
• GridView code in JAVA:
gv=(GridView)findViewById(R.id.gridview);
gv.setAdapter(adapter);
GridView
 Attributes or Properties of GridView
Sr Attribute
No.
1 android:id: id is used to uniquely identify a GridView. This can be retrieved
using findViewById() method. Ex: android:id="@+id/tb”
2 android:numColumns: used to 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.
If we don’t specify numColumn property in GridView it behaves like
a ListView with singleChoice.

3 android: horizontalSpacing: used to define the default horizontal spacing


between columns
4 android:verticalSpacing : used to define the default vertical spacing
between rows.

5 android:columnWidth: specifies the fixed width of each column


6 android: listSelector: This specifies color of selected item
Example of GridView
Contents of activity_main.xml file
<?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">

<GridView
android:id="@+id/gridview"
android:layout_width="fill_parent“
android:layout_height="wrap_content“
android:padding="1dp“
android:numColumns="3" />

</LinearLayout>
Example of GridView
Contents of MainActivity.java file
package com.example.griddemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.GridView;

public class MainActivity extends Activity {


GridView gv;
ArrayAdapter adapter;
String[] animals = {"Lion","Tiger","Monkey","Elephant","Dog","Cat","Camel"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gv=(GridView) findViewById(R.id.gridview);
ArrayAdapter<String> adapter=new
ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,animals);
gv.setAdapter(adapter);
}
Event Handling on ListView and GridView
• To handle the item click events we need to
use setOnItemClickListener method of AdapterView class
listview.setOnItemClickListener(new
AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View
view, int position, long id)
{
String s=adapter.getItem(position);
// String s = ((TextView)view).getText().toString();
Toast.makeText(getApplicationContext(),"You have
selected "+s, Toast.LENGTH_LONG).show();
}
});
Difference between ListView & GridView
ListView GridView

ListView used to show the GridView used to show the


collection of items in a elements in a two dimensional
vertically-scrollable list. scrollable view.

In this no need to mention In this number of columns need


number of columns. to be mentioned.

Ex: Contact List Ex: Gallary


<ListView <GridView
android:id="@+id/animal" android:id="@+id/grid"
android:layout_width="match_parent" android:layout_width="match_parent"
android:layout_height="wrap_content“ android:layout_height="wrap_content“
/> android:numColumns=“3”/>
ImageView
• ImageView class is used to display an image file in
application
• It supports different scale types.
• ImageView is subclasses of View
• Scale types are used to control how the image should
be re-sized or moved to match the size of image
view.
• Scale type for ImageView are CENTER,
CENTER_CROP, CENTER_INSIDE, FIT_CENTER,
FIT_END, FIT_START, FIT_XY and MATRIX.
ImageView
 Creation of ImageView:
• ImageView code in XML:
<ImageView
android:id="@+id/imageview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion"
• ImageView code in JAVA:
iv=(ImageView)findViewById(R.id.imageview);
ImageView
 Attributes or Properties of ImageView
Sr Attribute
No.
1 android:id: id is used to uniquely identify a ImageView. This can be
retrieved using findViewById() method. Ex: android:id="@+id/tb”
2 android:src: used to set an imagefile.

3 android: background: used to set the background of a ImageView. We can


set a color or a drawable in the background of a ImageView.
4 android:padding : used to set the padding from left, right, top or bottom
of the Imageview.

5 android:scaleType: used to control how the image should be re-sized or


moved to match the size of this image view. Values are CENTER,
CENTER_CROP, CENTER_INSIDE, FIT_CENTER, FIT_END, FIT_START, FIT_XY
and MATRIX
ImageView
• ImageView Different ScaleTypes :
1. CENTER – Center the image but doesn’t scale the image
2. CENTER_CROP – Scale the image uniformly
3. CENTER_INSIDE – Center the image inside the container,
rather than making the edge match exactly
4. FIT_CENTER – Scale the image from center
5. FIT_END – Scale the image from the end of the container.
6. FIT_START – Scale the image from start of the container
7. FIT_XY – Fill the image from x and y coordinates of the
container
8. MATRIX – Scale using the image matrix when drawing
Example of ImageView
Contents of activity_main.xml 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“>

<ImageView
android:id="@+id/imageview"
android:layout_width="fill_parent“
android:layout_height=“200dp“
android:src=“@drawable/rose" />

</RelativeLayout>
Example of ImageView
Contents of MainActivity.java file
package com.example.imageviewdemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}
}
ScrollView & HorizontalScrollView
• It is a view group that allows the view hierarchy placed
within it to be scrolled.
• Scroll view and HorizontalScrollView can have only one
direct child placed within it.
• To add multiple views within the scroll view, we need to
use different layouts like TableLayout, RelativeLayout
Linear Layout.
• ScrollView and HorizontalScrollView are subclasses
of FrameLayout.
• Scroll view supports vertical scrolling only. For horizontal
scrolling, use HorizontalScrollView.
• Never add a ListView to a scroll view. List View is default
scrollable.
ScrollView and HorizontalScrollView
• Creation of ScrollView • Creation of
• code in XML: HorizontalScrollView
<ScrollView • code in XML:
android:id="@+id/scrollView“
<HorizontalScrollView
android:layout_width="fill_parent“
android:id="@+id/hscrollView“
android:layout_height="fill_parent">
android:layout_width="fill_parent“
android:layout_height="fill_parent">
<!-- add child view’s here -->
<!-- add child view’s here -->
</ScrollView>
</HorizontalScrollView>
ScrollView
 Attributes or Properties of ScrollView

Sr Attribute
No.
1 android:id: id is used to uniquely identify a ScrollView. This can be
retrieved using findViewById() method. Ex: android:id="@+id/tb”
2 android:scrollbars: used to show the scrollbars in horizontal or vertical
direction. The possible Value of scrollbars is vertical, horizontal or none.
By default scrollbars is shown in vertical direction in scrollView and in horizontal
direction in HorizontalScrollView.
Example of ScrollView
Contents of activity_main.xml 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”>

<ScrollView android:layout_marginTop="30dp"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/scrollView">

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:layout_width="fill_parent" <Button
android:layout_height="wrap_content" android:layout_width="fill_parent"
android:text="Button 1" /> android:layout_height="wrap_content"
android:text="Button 6" />
<Button
<Button
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:text="Button 2" /> android:text="Button 7" />
<Button <Button
android:layout_width="fill_parent" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_height="wrap_content"
android:text="Button 8" />
android:text="Button 3" /> <Button
<Button android:layout_width="fill_parent"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:layout_height="wrap_content" android:text="Button 9" />
android:text="Button 4" /> <Button
android:layout_width="fill_parent"
<Button
android:layout_height="wrap_content"
android:layout_width="fill_parent" android:text="Button 10" />
android:layout_height="wrap_content"
android:text="Button 5" /> </LinearLayout>
</ScrollView
</RelativeLayout>
Example of ScrollView
Contents of MainActivity.java file
package com.example.scrollviewdemo;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ScrollView;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}
}
Toast
• Toast is a small popup notification.
• Toast is used to display information for a certain amount of
time and automatically disappear after a timeout.
• A Toast can be displayed for either 2 seconds
(Toast.LENGTH_SHORT) or 3.5 seconds (Toast.LENGTH_LONG).
• For example, clicking Send on an email triggers a "Sending
message..." toast, as shown in the following screen capture:

• Use it to show alert message to user.


• Toasts are not clickable. Toast has no focus.
• Toast class is the subclass of java.lang.Object class.
• Features of Toast
– It is an Android widget that is used to show a message for
a short duration of time.
– It disappears after a short time.
– It doesn't block the Activity or Fragment when it runs.
– It can be used to give feedback to the user regarding any
operations, like form submission etc.
• Contants of Toast class/ Duration of toast
public static final int LENGTH_LONG displays toast for the long duration of time
(3.5 sec )
public static final int LENGTH_SHORT displays toast for the short duration of
time. (2 sec )
 Creation of Toast:
Step 1) Create a Toast by instantiating Toast object using
makeText() method.
• makeText() takes three parameters:
– the application Context,
– the text message, and
– the duration for the toast.
Step 2)To display the toast notification we need to call show()

• Syntax:
Toast.makeText(context, "message", duration).show();
• Example:
Toast.makeText(MainActivity.this, ”Clicked on Button",
Toast.LENGTH_SHORT).show();
• Methods of Toast
void setGravity(int gravity, int xOffset, int Set the location at which the notification should
yOffset) appear on the screen.
First parameter can be:
Gravity.TOP, Gravity.LEFT, Gravity.RIGHT,
Gravity.BOTTOM, Gravity.CENTER_HOROZONTAL,
Gravity.CENTER, Gravity.CENTER_VERTICAL
void setDuration(int duration) Set how long to show the view for.

void setText(CharSequence s) Update the text in a Toast that was previously created
using one of the makeText() methods.
void show() Show the view for the specified duration.

static Toast makeText(Context context, Make a standard toast that just contains text.
CharSequence text, int duration)
void setMargin(float hMargin, float vMargin) Set the margins of the view.

int getGravity() Get the location at which the notification should


appear on the screen.
int getDuration() Return the duration.
Example of Toast
Contents of activity_main.xml 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“>

<Button
android:id="@+id/bt"
android:layout_width=“wrap_content“
android:layout_height=“wrap_content“
android:onClick=“submit”
android:text=“Button" />

</RelativeLayout>
Example of Toast
Contents of MainActivity.java file
package com.example.toastdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {


Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button) findViewById(R.id.bt);
}
public void submit(View v)
{ Toast.makeText(MainActivity.this, ”Clicked on Button..",
Toast.LENGTH_SHORT).show();
}
}
Custom Toast Alert

• Custom Toast can be used to display the Toast with images,


Toast in specified location, etc.
• From API level 30 , Custom toast views are deprecated.
• Steps:
1. To create a custom Toast notification, create a custom XML
file (custom_toast.xml) in layout (/layout) folder. Add
ImageView and TextView using LinearLayout.
2. LayoutInflater is a class used to instantiate layout XML file
into its view objects.
3. In MainActivity, Create instance of LayoutInflator as
LayoutInflator inf=getLayoutInflator();
View vw=View.inflate(this,R.layout.custom_toast,(ViewGroup)
findViewById(R.id.toast_container));
Custom Toast Alert
4. Create Toast object and set duration,gravity and view. as
follows
Toast toast= new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_HORIZONTAL,0,180);
toast.setView(vw);
5. Display toast using show()
toast.show();
custom_toast.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_container"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#80CC28">

<ImageView
android:layout_width="80dp"
android:layout_height="49dp"
android:layout_marginRight="10dp"
android:src="@drawable/rose" />

<TextView
android:id="@+id/txtvw"
android:layout_width="281dp"
android:layout_height="36dp"
android:layout_marginTop="13dp"
android:textColor="#FFF"
android:textSize="15dp“
android:text="This is Custom Toast"/>
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“">

<Button
android:id="@+id/b1"
android:layout_width=“wrap_content"
android:layout_height=“wrap_content"
android:layout_marginTop="100dp“
android:layout_centerHorizontal="true"
android:text=“Custom Toast Demo”/>

</RelativeLayout>
MainActivity.java
package com.example.customtoast;

import android.app.Activity;
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.Toast;

public class MainActivity extends Activity {

Button b1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=findViewById(R.id.b1);
}
public void submit(View v)
{
LayoutInflater inf=getLayoutInflater();
View vw=View.inflate(this,R.layout.custom_toast,
(ViewGroup) findViewById(R.id.toast_container));
Toast toast= new Toast(getApplicationContext());
toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER_HORIZONTAL,0,180);
toast.setView(vw);
toast.show();
}
}
DatePicker
• DatePicker is used to select a date.
• It allows to select date by day, month and year.
• Date pickers helps to ensure that users can pick a date
that is valid, formatted correctly, and adjusted to the
user's locale.
• If we need to show DatePicker view as a dialog then we
have to use a DatePickerDialog class. DatePickerDialog
is a simple dialog containing DatePicker.
• DatePicker is the subclass of FrameLayout class.
• Date Picker is available in two modes either spinner or
calendar. Calendar mode is deprecated after API level
21.
Creating Date Picker
• Creating a Date Picker
• Code in XML
<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:datePickerMode="spinner" />

• Code in Java
DatePicker datepicker=findViewById(R.id.datePicker);
Methods of Date Picker
1 getDayOfMonth() This method gets the selected day of month
2 getMonth() This method gets the selected month. month is 0 based
3 getYear() This method gets the selected year
4 setMaxDate(long maxDate) This method sets the maximal date
supported by this DatePicker in milliseconds since January 1, 1970
00:00:00 in getDefault() time zone

5 setMinDate(long minDate) This method sets the minimal date


supported by this DatePicker in milliseconds since January 1, 1970
00:00:00 in getDefault() time zone

6 setSpinnersShown(boolean shown) This method sets whether the


spinners of the date picker are shown or not
7 updateDate(int year, int month, int dayOfMonth) This method
updates the current date.
8 getCalendarView() This method returns calendar view
9 getFirstDayOfWeek() This Method returns first day of the week
 Attributes or Properties of DatePicker
Sr Attribute
No.
1 android:id: id is used to uniquely identify a DatePicker. This can be
retrieved using findViewById() method. Ex: android:id="@+id/datePicker”
2 android:datePickerMode: used to set the Date Picker in mode either
spinner or calendar.
3 android: background: used to set the background of a DatePicker. We can
set a color or a drawable in the background.
4 android:padding : used to set the padding from left, right, top or bottom
of the DatePicker.
5 android:calendarViewShown: Whether the calendars are shown. If true
then calendar is shown.
6 android:dayOfWeekBackground:The background color for the header's day of
week.

7 android:spinnersShown: Whether the spinners are shown or not. If true then


spinner is shown.
Example of DatePicker
Contents of activity_main.xml 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“>

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

<Button
android:id="@+id/bt"
android:layout_width=“wrap_content“
android:layout_height=“wrap_content“
android:onClick=“submit”
android:text=“Button" /> </RelativeLayout>
Example of DatePicker
Contents of MainActivity.java file
package com.example.datepickerdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.DatePicker;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {


Button b1;
DatePicker datepicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button) findViewById(R.id.bt);
datepicker=(DatePicker) findViewById(R.id.datePicker);
}
public void submit(View v)
{
int d=datepicker.getDayOfMonth();
int m=datepicker.getMonth() + 1;
int y= datepicker.getYear();

String date=d+“/”+m+”/”+y;

Toast.makeText(this, ”Selected Date is “+date, Toast.LENGTH_LONG).show();


}
}
• Event Handling on DatePicker
1)onClick attribute
2)OnClickListener
3)OnDateChangedListener

• DatePicker.OnDateChangedListener is used indicates the user


changed the date.
• onDateChanged() method is called upon date change.
• Syntax:
public void onDateChanged (DatePicker view, int year, int month,
int day)
{
//code
}
• Event Handling on DatePicker
Ex:
datepicker. setOnDateChangedListener(new
DatePicker.OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year, int
month,int day)
{
Toast.makeText(getApplicationContext(), day + “/ " +
(month+1)+”/”+year, Toast.LENGTH_SHORT).show();
}
});
Time Picker
• TimePicker is used for selecting the time of the day in either
AM/PM mode or 24 hours mode.
• The displayed time consist of hours, minutes and clock format.
• It allows you to select time by hour and minute. You cannot
select time by seconds.
• If we need to show time picker as a Dialog then we have to use
a TimePickerDialog class.
• TimePicker is the subclass of FrameLayout class.
Creating Time Picker
• Creating a TimePicker
• Code in XML
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner" />

• Code in Java
TimePicker timepicker=findViewById(R.id.timePicker);
Methods of Time Picker
1 is24HourView()
This method returns true if this is in 24 hour view else false
2 isEnabled()
This method returns the enabled status for this view
3 setCurrentHour(Integer currentHour)
This method sets the current hour .
setCurrentHour() method was deprecated in API level 23. From api
level 23 we have to use setHour(Integer hour).
4 setCurrentMinute(Integer currentMinute)
This method sets the current minute
setCurrentMinute() method was deprecated in API level 23. From
api level 23 we have to use setMinute(Integer minute).
5 setEnabled(boolean enabled)
This method set the enabled state of this view

6 setIs24HourView(Boolean is24HourView)
This method set whether in 24 hour or AM/PM mode
Methods of Time Picker
7 setOnTimeChangedListener(TimePicker.OnTimeChangedListener
onTimeChangedListener)
This method Set the callback that indicates the time has been
adjusted by the user
8 int getCurrentHour()
This method returns the current hour
getCurrentHour() method was deprecated in API level 23. From api
level 23 you have to use getHour(). This method returns an integer
value.
9 int getCurrentMinute()
This method returns the current minute
getCurrentMinute() method was deprecated in API level 23. From
api level 23 we have to use getMinute().
TimePicker
 Attributes or Properties of TimePicker

Sr Attribute
No.
1 android:id: id is used to uniquely identify a TimePicker. This can be
retrieved using findViewById() method. Ex: android:id="@+id/timePicker”
2 android:timePickerMode: used to set the Date Picker in mode either
spinner or clock. Default mode is clock. Clock mode is no longer used after api
level 21.
3 android: background: used to set the background of a DatePicker. We can
set a color or a drawable in the background.
4 android:padding : used to set the padding from left, right, top or bottom
of the Imageview.
• Event Handling on TimePicker
1)onClick attribute
2)OnClickListener
3)OnTimeChangedListener

• TimePicker.OnTimeChangedListener is used indicates the user


changed the time.
• onTimeChanged() method is called upon time change.
• Syntax:
public void onTimeChanged (TimePicker view, int hour, int minute)
{
//code
}
• Event Handling on TimePicker
Ex:
timepicker. setOnTimeChangedListener(new
TimePicker.OnDateChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hour, int
minute)
{
Toast.makeText(getApplicationContext(), hour + “: " + minute,
Toast.LENGTH_SHORT).show();
}
});
Example of TimePicker
Contents of activity_main.xml 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“>

<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content“
android:layout_height="wrap_content“
android:timePickerMode="spinner" />
</RelativeLayout>
Example of TimePicker
Contents of MainActivity.java file
package com.example.datepickerdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity {


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

timepicker=(TimePicker) findViewById(R.id.timePicker);
timepicker.setIs24HourView(false); // used to display AM/PM mode i.e 12 hour
Example of TimePicker

timepicker. setOnTimeChangedListener(new TimePicker.OnTimeChangedListener()


{

public void onTimeChanged(TimePicker view, int hour, int minute)


{
Toast.makeText(getApplicationContext(), hour+ " " + minute,
Toast.LENGTH_SHORT).show();
}
});
}

You might also like