You are on page 1of 94

Unit 3 : User Interface Screen Elements

1. Toast & Snack Bar


2. Custom Toast
3. Button
a. Toggle Button
b. Switch Button
c. Image Button
d. Radio Button

4. TextView and EditText, CheckBox


5. Alert Dialog and Button Sheets
6. Spinner
7. Date Picker and Time Picker
8. Rating Bar and Progress Bar
9. File Download
Android Toast and Snack Bar

Toast
● Android Toast can be used to display information for the short period
of time.
● A toast contains message to be displayed quickly and disappears
after sometime.
● The android.widget.Toast class is the subclass of java.lang.Object
class.
● You can also create custom toast as well for example toast
displaying image.

Toast Class

● Toast class is used to show notification for a particular interval of


time. After sometime it disappears. It doesn't block the user
interaction.

Constants of Toast class

There are only 2 constants of Toast class which are given below.

Constant Description

public static final int LENGTH_LONG displays view for the long duration of time.

public static final int LENGTH_SHORT displays view for the short duration of time.
Methods of Toast class

The widely used methods of Toast class are given below.

Method Description

public static Toast makeText(Context context, CharSequence text, int makes the toast containing text and duration.
duration)

public void show() displays toast.

public void setMargin (float horizontalMargin, float verticalMargin) changes the horizontal and vertical margin
difference.

Android Toast Example

Toast.makeText(getApplicationContext(),
"Hello My First Toast",
Toast.LENGTH_SHORT).show();

Another code:

...
Toast toast = Toast.makeText(getApplicationContext(),
"Hello Toast",
Toast.LENGTH_SHORT);
toast.setMargin(50,50);
toast.show();
...
● Here, getApplicationContext() method returns the instance of
Context.
● Full code of activity class displaying Toast

Let's see the code to display the toast.

File: MainActivity.java

package com.example.toast;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

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

//Displaying Toast with ‘Hello My First Toast’ message


Toast.makeText(getApplicationContext(),"This is a Toast
message",Toast.LENGTH_SHORT).show();
}
}
Output

:
Snackbar
● When Android 5.0 was released, new design guidelines were also
released with it, called material design. (Material design in a way
revamped the experience of an android user. It introduced many new
design patterns and guidelines.)
● This new concept is inspired from the Toast widget of android.
Android Snackbar is just like a Toast message except that it has an
option for user feedback.
● Usually this type of widget is used in a situation where the user needs
an option to reverse his actions like undo -ing an action or retrying an
action that had failed.
● Android Snackbar using the new Design Support Library.
● To make an Android Snackbar many libraries are available on the
internet. But for this Android Snackbar Example we will be using the
official Android design support library which was released in the
beginning of June 15.
● Snackbars disappear automatically, either after a timeout or after a
user interaction elsewhere on the screen, and can also be swiped off
the screen.

Usage

● The Snackbar class provides static make methods to produce a


snackbar configured in the desired way.
● These methods take a View, which will be used to find a suitable
ancestor ViewGroup to display the snackbar in, a text string to display
(either as a CharSequence or a resource ID), and a duration to display
the snackbar for (either a duration preset, or a time in milliseconds).
● A suitable ancestor ViewGroup will be either the nearest
CoordinatorLayout to the View passed in, or the root DecorView if
none could be found.
Available duration presets are:

1. LENGTH_INDEFINITE
2. LENGTH_LONG
3. LENGTH_SHORT

NOTE: Snackbar work best if they are displayed inside of a


CoordinatorLayout. CoordinatorLayout allows the snackbar to
enable behavior like swipe-to-dismiss, as well as automatically
moving widgets like FloatingActionButton.

● Calling make only creates the snackbar, it doesn’t actually cause it to


be visible on the screen. For showing the snackbar, use the show
method on the returned Snackbar instance.
● Note that only one snackbar will be shown at a time. Showing a new
snackbar will dismiss any previous ones first.
● Showing a snackbar with just a message and no action would look
like this:

// The view used to make the snackbar. This should be contained within the view
// hierarchy you want to display the snackbar. Generally it can be the view that
// was interacted with to trigger the snackbar, such as a button that was
// clicked, or a card that was swiped.
Code Snippet :

View contextView = findViewById(R.id.context_view);



Snackbar.make(
contextView,
R.string.item_removed_message,
Snackbar.LENGTH_SHORT
).show();

Android Snackbar Example using Design Support Library

● To start off lets include the Android design support library in our
project gradle file:

build.gradle (app)
compile 'com.android.support:design:22.2.0'

Displaying an Android Snackbar on your screen is very simple, all you need
to do is use this piece of code below:

Java
Snackbar.make(findViewById(android.R.id.content),
"Had a snack at Snackbar",
Snackbar.LENGTH_LONG)
.setAction("Undo", mOnClickListener)
.setActionTextColor(Color.RED)
.show();

EXAMPLE PERFORMED IN LECTURE.


Difference between Toast and Snackbar
1. A Toast messages can be customised and printed anywhere on the
screen, but a Snackbar can be only showed in the bottom of the
screen
2. A Toast message doesn't have an action button, but Snackbar may
have an action button optionally. Though, A Snackbar shouldn’t have
more than one action button
3. Toast message cannot be off until the time limit finish, but Snackbar
can be swiped off before the time limit

Note: Toast message and Snackbar have display length


property in common.
Android Custom Toast Example
Check the Reference link for more detail

● If a simple text message in toast isn't enough, you can create a customized
layout for your toast notification.
● To create a custom layout, define a View layout, in XML or in your application
code, and pass the root View object to the setView(View) method.
● The following snippet contains a customized layout for a toast notification
(saved as layout/custom_layout_for_toast.xml):

File location and Filename layout/custom_layout_for_toast.xml

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


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#64B5F6"
android:padding="16dp"
android:gravity="center_vertical"
android:orientation="horizontal">

<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher_round" />

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World"
android:textColor="#00f"
android:layout_marginStart="16dp"
android:textSize="30sp" />

</LinearLayout>
Preview of custom_layout_for_toast.xml file

● Notice that the ID of the XML layout file is "custom_layout_for_toast" to inflate


the layout, as shown here:

Code Snippet to Inflate custom layout in Toast

LayoutInflater inflater = getLayoutInflater();


View vToast = inflater.inflate(R.layout.custom_layout_for_toast,
null);

Toast toast = new Toast(getApplicationContext());


toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.setView(vToast);

toast.show();

Following is the whole code in MainActivity.java


File location and Filename java/com/ndroid/customtoast/MainActivity.java

package com.ndroid.customtoast;

import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

LayoutInflater inflater = getLayoutInflater();


View vToast =
inflater.inflate(R.layout.custom_layout_for_toast, null);

Toast toast = new Toast(getApplicationContext());


toast.setDuration(Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.setView(vToast);

toast.show();
}
}

Output :
Button
a. Toggle Button

b. Switch Button

c. Image Button

d. Radio Button
Toggle Button

● Android Toggle Button can be used to display checked/unchecked


(On/Off) state on the button.
● It is beneficial if a user has to change the setting between two states.
It can be used for On/Off Sound, Show/Hide Password, etc.
● Since Android 4.0, there is another type of toggle button called switch
that provides slider control.

● Android ToggleButton and Switch both are the subclasses of


CompoundButton class.
● Hierarchy Classes :
Object > View > TextView > Button > CompoundButton > ToggleButton

Android ToggleButton class

ToggleButton class provides the facility of creating the toggle button.


XML Attributes of ToggleButton class

The 3 XML attributes of the ToggleButton class.

XML Attribute Description

android:disabledAlpha The alpha to apply to the indicator when


disabled.
android:textOff The text for the button when it is not
checked.
android:textOn The text for the button when it is
checked.

Methods of ToggleButton class


The widely used methods of the ToggleButton class are given below.

Method Description

CharSequence getTextOff() Returns the text when the


button is not in the checked
state.
CharSequence getTextOn() Returns the text for when the
button is in the checked state.
void setChecked(boolean Changes the checked state of
checked) this button.
Android ToggleButton Example

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


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

<ToggleButton
android:id="@+id/toggleButtonA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ToggleButton"
android:layout_gravity="center"
android:textOff="Off"
android:textOn="On" />

</FrameLayout>
Activity class
Let's write the code to check which toggle button is ON/OFF.

File: MainActivity.java
package com.ndroid.togglebutton;

import androidx.appcompat.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 {


private ToggleButton toggleButton1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initObject();
addListeners();
}

public void initObject() {


//Getting the ToggleButton and Button instance from the layout xml file
toggleButton1 = (ToggleButton) findViewById(R.id.toggleButtonA);
}

public void addListeners() {


//Performing action on toggle button clicked
toggleButton1.setOnCheckedChangeListener( new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton toggleButton, boolean isChecked)
{
if(isChecked)
showMsg("Toggle button was On") ;
else
showMsg("Toggle button was Off") ;
}
}) ;
}
}

File: activity_main.xml

Output:
Switch Button
● In android, Switch is a two-state user interface element which is used
to display ON (Checked) or OFF (Unchecked) states as a button with
thumb slider. By using thumb, the user may drag back and forth to
choose an option either ON or OFF.
● The Switch element is useful for the users to change the settings
between two states either ON or OFF. We can add a Switch to our
application layout by using Switch object.
● Following is the pictorial representation of using Switch in android
applications.

● By default, the android Switch will be in OFF (Unchecked) state. We


can change the default state of Switch by using
android:checkedattribute.
● In case, if we want to change the state of Switch to ON (Checked),
then we need to set android:checked = “true” in our XML layout file.
● In android, we can create Switch control in two ways either in XML
layout file or create it in Activity file programmatically.

Create Switch in XML Layout File

Following is the sample way to define Switch control in XML layout file in
android application.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:switchMinWidth="56dp"
android:layout_marginLeft="100dp"
android:layout_marginTop="120dp"
android:text="Switch1:"
android:checked="true"
android:textOff="OFF"
android:textOn="ON"/>
</RelativeLayout>

● If you observe above code snippet, here we defined Switch control


and setting Switch state ON using android:checked attribute and
textOff / textOn attributes are used to set the text to represent Switch
state in xml layout file.
Create Switch Control in Activity File

● In android, we can create Switch control programmatically in activity


file based on our requirements.

Following is the example of creating Switch control dynamically in activity


file.
RelativeLayout layout = (RelativeLayout)findViewById(R.id.r_layout);
Switch sb = new Switch(this);
sb.setTextOff("OFF");
sb.setTextOn("ON");
sb.setChecked(true);
layout.addView(sb);

This is how we can define Switch in XML layout file or programmatically in


activity file based on our requirements.

Handle Switch Click Events

Generally, whenever the user clicks on Switch, we can detect whether the
Switch is in ON or OFF state and we can handle Switch click event in
activity file using setOnCheckedChangeListener like as shown below.

Switch sw = (Switch) findViewById(R.id.switch1);


sw.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// The toggle is enabled
} else {
// The toggle is disabled
}
}
});

This is how we can handle Switch click events in android applications


based on our requirements.
Android Switch Control Attributes

Following are the some of commonly used attributes related to Switch


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 switch 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:textOn It is used to set the text when toggle button is in ON /


Checked state.

android:textOff It is used to set the text when toggle button is in 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:drawableBo It’s a drawable to be drawn to the below of text.


ttom

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


ght
android:drawableLe It’s a drawable to be drawn to the left of text.
ft

Android Switch Control Example

Following is the example of defining a two Switch controls and one Button
control in RelativeLayout to get the state of Switch controls when we click
on Button control in android application.

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

Now open an activity_main.xml file from \res\layout path and write the
code like as shown below
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="120dp"
android:checked="true"
android:switchMinWidth="56dp"
android:text="Switch1:" />

<Switch
android:id="@+id/switch2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/switch1"
android:layout_alignLeft="@+id/switch1"
android:switchMinWidth="56dp"
android:text="Switch2:"
android:textOff="Band"
android:textOn="Challu" />

<Button
android:id="@+id/btnGetValues"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="150dp"
android:layout_marginTop="200dp"
android:text="Get Value of Switch" />
</RelativeLayout>
If you observe above code we defined a two Switch controls and one
Button control in RelativeLayout to get the state of Switch controls when
we click on Button control in XML layout file.

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

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Switch;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


private Switch sw1,sw2;
private Button btnGet;

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

initObjects();
addListeners();
}

private void initObjects() {


sw1 = findViewById(R.id.switch1);
sw2 = findViewById(R.id.switch2);
btnGet = findViewById(R.id.btnGetValues);
}

private void addListeners() {


btnGet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String str1, str2;

if (sw1.isChecked())
str1 = "Switch 1 is On";
else
str1 = "Switch 1 is Off";
if (sw2.isChecked())
str2 = sw2.getTextOn().toString();
else
str2 = sw2.getTextOff().toString();

showMsg("Switch1 - " + str1 + " \n" + "Switch2 - " + str2);


}
});
}

private void showMsg(String msg)


{
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
}

If you observe above code we are calling our layout using setContentView
method in the form of R.layout.layout_file_name in our activity file. Here our
xml file name is activity_main.xml so we used file name activity_main and
we are trying to get the state of two Switch controls on Button click.

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

When we run above example using android virtual device (AVD) we will get
a result like as shown below.
Image Button
● Object > View > ImageView > ImageButton
● It Resides in android.widget.ImageButton package
● An ImageButton is an AbsoluteLayout which enables you to specify
the exact location of its children.
● This shows a button with an image (instead of text) that can be
pressed or clicked by the user.

ANDROID BUTTON STYLE SET


ImageButton Attributes

Following are the important attributes related to ImageButton control. You


can check Android official documentation for complete list of attributes
and related methods which you can use to change these attributes are run
time.
Inherited from android.widget.ImageView Class −
Sr.No Attribute & Description

android:adjustViewBounds
Set this to true if you want the ImageView to adjust its
1
bounds to preserve the aspect ratio of its drawable.

android:baseline
2 This is the offset of the baseline within this view.

android:baselineAlignBottom
If true, the image view will be baseline aligned with based on
3
its bottom edge.

android:cropToPadding
4 If true, the image will be cropped to fit within its padding.

android:src
5 This sets a drawable as the content of this ImageView.
Inherited from android.view.View Class −
Sr.No Attribute & Description

1 android:background
This is a drawable to use as the background.

2 android:contentDescription
This defines text that briefly describes content of the view.

3 android:id
This supplies an identifier name for this view

4 android:onClick
This is the name of the method in this View's context to invoke
when the view is clicked.

5 android:visibility
This controls the initial visibility of the view.
Example
This example will take you through simple steps to show how to create
your own Android application using Linear Layout and ImageButton.
Step Description

1 You will use Android studio IDE to create an Android application


and name it as myapplication under a package
com.example.myapplication as explained in the Hello World
Example chapter.

2 Modify src/MainActivity.java file to add a click event.

3 Modify the default content of res/layout/activity_main.xml file to


include Android UI control.

4 No need to define default constants in android, Android studio


takes care of default constants.

5 Run the application to launch Android emulator and verify the


result of the changes done in the application.

Following is the content of the modified main activity file


src/com.example.myapplication/MainActivity.java. This file can include
each of the fundamental lifecycle methods.
In the below example abc indicates the image of tutorialspoint
package com.example.myapplication;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.Toast;

public class MainActivity extends Activity {


ImageButton imgButton;

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

imgButton =(ImageButton)findViewById(R.id.imageButton);
imgButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),"You download is
resumed",Toast.LENGTH_LONG).show();
}
});
}
}

Following will be the content of res/layout/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"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">

<TextView android:text="Hinduja College"


android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30dp"
android:layout_alignParentTop="true"
android:layout_alignRight="@+id/imageButton"
android:layout_alignEnd="@+id/imageButton" />

<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageButton"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="@drawable/abc"/>

</RelativeLayout>
Following will be the content of res/values/strings.xml to define these new
constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">Image Button</string>
</resources>

Following is the default content of AndroidManifest.xml −


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

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.myapplication.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>
</application>
</manifest>
Radio Button
● RadioButton is a two states button which is either checked or
unchecked. If a single radio button is unchecked, we can click it to
make checked radio button. Once a radio button is checked, it cannot
be marked as unchecked by user.
● RadioButton is generally used with RadioGroup. RadioGroup contains
several radio buttons, marking one radio button as checked makes all
other radio buttons as unchecked.

Example of Radio Button


In this example, we are going to implement single radio button separately
as well as radio button in RadioGroup.

activity_main.xml
File: 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"
tools:context="example.javatpoint.com.radiobutton.MainActivity">

<TextView
android:id="@+id/textView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center_horizontal"
android:textSize="22dp"
android:text="Single Radio Buttons" />

<!-- Default RadioButtons -->

<RadioButton
android:id="@+id/radioButton1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Radio Button 1"
android:layout_marginTop="20dp"

android:textSize="20dp" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Radio Button 2"
android:layout_marginTop="10dp"

android:textSize="20dp" />

<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:layout_marginTop="20dp"
android:background="#B8B894" />

<TextView
android:id="@+id/textView2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:gravity="center_horizontal"
android:textSize="22dp"
android:text="Radio button inside RadioGroup" />

<!-- Customized RadioButtons -->

<RadioGroup
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/radioGroup">

<RadioButton
android:id="@+id/radioMale"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" Male"
android:layout_marginTop="10dp"
android:checked="false"
android:textSize="20dp" />

<RadioButton
android:id="@+id/radioFemale"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" Female"
android:layout_marginTop="20dp"
android:checked="false"

android:textSize="20dp" />
</RadioGroup>

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Selected"
android:id="@+id/button"
android:onClick="onclickbuttonMethod"
android:layout_gravity="center_horizontal" />

</LinearLayout>
Activity class
File: MainActivity.java
package com.ndroid.radiobutton;

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.RadioGroup;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


Button button;
RadioButton genderradioButton;
RadioGroup radioGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
radioGroup=(RadioGroup)findViewById(R.id.radioGroup);
}
public void onclickbuttonMethod(View v){
int selectedId = radioGroup.getCheckedRadioButtonId();
genderradioButton = (RadioButton) findViewById(selectedId);
if(selectedId==-1){
Toast.makeText(MainActivity.this,"Nothing selected",
Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(MainActivity.this,genderradioButton.getText(),
Toast.LENGTH_SHORT).show();
}

}
}

Output
TextView and EditText, CheckBox

TextView
● A TextView displays text to the user and optionally allows them to
edit it.
● A TextView is a complete text editor, however the basic class is
configured to not allow editing.

TextView Attributes
Following are the important attributes related to TextView control. You can
check Android official documentation for complete list of attributes and
related methods which you can use to change these attributes are run time.
Sr.No. Attribute & Description

1 android:id
This is the ID which uniquely identifies the control.

2 android:capitalize
If set, specifies that this TextView has a textual input method
and should automatically capitalize what the user types.
● 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

3 android:cursorVisible
Makes the cursor visible (the default) or invisible. Default is
false.
4 android:editable
If set to true, specifies that this TextView has an input
method.

5 android:fontFamily
Font family (named by string) for the text.

6 android:gravity
Specifies how to align the text by the view's x- and/or y-axis
when the text is smaller than the view.

7 android:hint
Hint text to display when the text is empty.

8 android:inputType
The type of data being placed in a text field. Phone, Date,
Time, Number, Password etc.

9 android:maxHeight
Makes the TextView be at most this many pixels tall.

10 android:maxWidth
Makes the TextView be at most this many pixels wide.

11 android:minHeight
Makes the TextView be at least this many pixels tall.

12 android:minWidth
Makes the TextView be at least this many pixels wide.
13 android:password
Whether the characters of the field are displayed as
password dots instead of themselves. Possible value either
"true" or "false".

14 android:phoneNumber
If set, specifies that this TextView has a phone number input
method. Possible value either "true" or "false".

15 android:text
Text to display.

16 android:textAllCaps
Present the text in ALL CAPS. Possible value either "true" or
"false".

17 android:textColor
Text color. May be a color value, in the form of "#rgb", "#argb",
"#rrggbb", or "#aarrggbb".

18 android:textColorHighlight
Color of the text selection highlight.

19 android:textColorHint
Color of the hint text. May be a color value, in the form of
"#rgb", "#argb", "#rrggbb", or "#aarrggbb".

20 android:textIsSelectable
Indicates that the content of a non-editable text can be
selected. Possible value either "true" or "false".
21 android:textSize
Size of the text. Recommended dimension type for text is "sp"
for scaled-pixels (example: 15sp).

22 android:textStyle
Style (bold, italic, bolditalic) for the text. You can use or more
of the following values separated by '|'.
● normal - 0
● bold - 1
● italic - 2

23 android:typeface
Typeface (normal, sans, serif, monospace) for the text. You
can use or more of the following values separated by '|'.
● normal - 0
● sans - 1
● serif - 2
● monospace - 3
Example
This example will take you through simple steps to show how to create
your own Android application using Linear Layout and TextView.
Step Description

1 You will use Android studio to create an Android application


and name it as demo under a package com.example.demo as
explained in the Hello World Example chapter.

2 Modify src/MainActivity.java file to add necessary code .

2 Modify the default content of res/layout/activity_main.xml file


to include Android UI control.

3 No need to change default string constants at string.xml file.


Android studio takes care of default string constants.

4 Run the application to launch Android emulator and verify the


result of the changes done in the application.

Following is the content of the modified main activity file


src/com.example.demo/MainActivity.java. This file can include each of the
fundamental lifecycle methods.
package com.example.demo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {


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

//--- text view---


TextView txtView = (TextView) findViewById(R.id.text_id);
}
}
Following will be the content of res/layout/activity_main.xml file −
<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" >

<TextView
android:id="@+id/text_id"
android:layout_width="300dp"
android:layout_height="200dp"
android:capitalize="characters"
android:text="hello_world"
android:textColor="@android:color/holo_blue_dark"
android:textColorHighlight="@android:color/primary_text_dark"
android:layout_centerVertical="true"
android:layout_alignParentEnd="true"
android:textSize="50dp"/>

</RelativeLayout>

Following will be the content of res/values/strings.xml to define two new


constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">TextView Demo</string>
</resources>

Following is the default content of AndroidManifest.xml −


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

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.demo.MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>

</application>
</manifest>
Let's try to run your demo application. I assume you had created your AVD
while doing environment setup. To run the app from Android studio, open
one of your project's activity files and click Run icon from the toolbar.
Android studio installs the app on your AVD and starts it and if everything is
fine with your setup and application, it will display following Emulator
window −
EditText :
● A EditText is an overlay over TextView that configures itself to be
editable.
● It is the predefined subclass of TextView that includes rich editing
capabilities.

STYLES OF EDIT TEXT

EditText Attributes
● Following are the important attributes related to EditText control.
● You can check Android official documentation for complete list of
attributes and related methods which you can use to change these
attributes are run time.

Inherited from android.widget.TextView Class −


Sr.No Attribute & Description

1 android:autoText
If set, specifies that this TextView has a textual input method
and automatically corrects some common spelling errors.
2 android:drawableBottom
This is the drawable to be drawn below the text.

3 android:drawableRight
This is the drawable to be drawn to the right of the text.

4 android:editable
If set, specifies that this TextView has an input method.

5 android:text
This is the Text to display.
Inherited from android.view.View Class −
Sr.No Attribute & Description

1 android:background
This is a drawable to use as the background.

2 android:contentDescription
This defines text that briefly describes content of the view.

3 android:id
This supplies an identifier name for this view.

4 android:onClick
This is the name of the method in this View's context to
invoke when the view is clicked.

5 android:visibility
This controls the initial visibility of the view.

Example
This example will take you through simple steps to show how to create
your own Android application using Linear Layout and EditText.
Step Description

1 You will use Android studio IDE to create an Android


application and name it as demo under a package
com.example.demo as explained in the Hello World Example
chapter.

2 Modify src/MainActivity.java file to add a click event.

3 Modify the default content of res/layout/activity_main.xml file


to include Android UI control.
4 Define required necessary string constants in
res/values/strings.xml file

5 Run the application to launch Android emulator and verify the


result of the changes done in the application.

Following is the content of the modified main activity file


src/com.example.demo/MainActivity.java. This file can include each of the
fundamental lifecycle methods.
package com.example.demo;

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

import android.view.View;
import android.view.View.OnClickListener;

import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {


EditText eText;
Button btn;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
eText = (EditText) findViewById(R.id.edittext);
btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String str = eText.getText().toString();
Toast msg = Toast.makeText(getBaseContext(),str,Toast.LENGTH_LONG);
msg.show();
}
});
}
}

Following will be the content of res/layout/activity_main.xml file −


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

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="14dp"
android:layout_marginTop="18dp"
android:text="@string/example_edittext" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="130dp"
android:text="@string/show_the_text" />

<EditText
android:id="@+id/edittext"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/button"
android:layout_below="@+id/textView1"
android:layout_marginTop="61dp"
android:ems="10"
android:text="@string/enter_text" android:inputType="text" />

</RelativeLayout>

Following will be the content of res/values/strings.xml to define these new


constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">demo</string>
<string name="example_edittext">Example showing EditText</string>
<string name="show_the_text">Show the Text</string>
<string name="enter_text">text changes</string>
</resources>

Following is the default content of AndroidManifest.xml −


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

<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >

<activity
android:name="com.example.demo.MainActivity"
android:label="@string/app_name" >

<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>

</activity>
</application>

</manifest>

Let's try to run your demo application. I assume you had created your
AVDwhile doing environment setup. To run the app from Android studio,
open one of your project's activity files and click Run icon from the
toolbar. Android Studio installs the app on your AVD and starts it and if
everything is fine with your setup and application, it will display following
Emulator window −
Alert Dialog and Button Sheets

activity_mail.xml

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


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

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:padding="16dp"
android:text="Press hardware back button to exit"
android:textColor="#f00"
android:textSize="30sp" />

</FrameLayout>
MainActivity.java

package com.example.mytoastandsnackbar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;

public class MainActivity extends Activity {

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

@Override
public void onBackPressed() {
//super.onBackPressed();
// Create the object of
// AlertDialog Builder class
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
//Setting Title
builder.setTitle("Attention!!");

//Setting Message
builder.setMessage("Do you want to exit from this Application ?");

// Set Cancelable false


// for when the user clicks on the outside
// the Dialog Box then it will remain show
builder.setCancelable(false);

// Set the positive button with yes name


// OnClickListener method is use of
// DialogInterface interface.
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
// Set the Negative button with No name
// OnClickListener method is use
// of DialogInterface interface.
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// If user click no
// then dialog box is canceled.
dialog.cancel();
}
});

// Create the Alert dialog


AlertDialog alertDialog = builder.create();
// Show the Alert Dialog box
alertDialog.show();
}
}
Spinner

string.xml
<resources>
<string name="app_name">Unit3</string>

<string-array name="array_countries">
<item>--Please select a country--</item>
<item>India</item>
<item>Sri Lanka</item>
<item>Bangladesh</item>
<item>Country 1</item>
<item>Country 2</item>
<item>Country 3</item>
</string-array>
</resources>

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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"
tools:context=".MainActivity">

<Spinner
android:id="@+id/spCounties"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginHorizontal="32dp"
android:entries="@array/array_countries"
android:paddingHorizontal="32dp"
android:spinnerMode="dialog" />

</FrameLayout>

MainActivity.java
package com.example.unit3;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


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

Spinner spinner = findViewById(R.id.spCounties);


spinner.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int
iPosition, long id) {
String[] strCounties =
getResources().getStringArray(R.array.array_countries);
showMsg("position " + iPosition + " Value is " +
strCounties[iPosition]);
}

@Override
public void onNothingSelected(AdapterView<?> adapterView) {

}
});

private void showMsg(String msg) {


Toast.makeText(getApplicationContext(), msg,
Toast.LENGTH_LONG).show();
}
}
Date Picker and Time Picker
DatePicker and TimePicker are all extends android.widget.FrameLayout.
They are used to display date and time selection widget in android
application. They can be used in either spinner mode or calendar mode (
date picker), clock mode ( time picker ). You can control their appearance
with their properties.

DatePicker Properties :
1. datePickerMode : Value can be spinner or calendar. If set to
calendar, it will display a calendar which let you choose date.
If set to spinner, it will display a spinner to let you choose
date.
DatePicker Calendar Mode
DatePicker Spinner Mode

2. calendarViewShown : This is a boolean value, only take effect


when datePickerMode is spinner. If set to true, it will display
a calendar.
3. spinnersShown : This is a boolean value also, only take effect
when datePickerMode is spinner. If set to true, it will display
a spinner.
4. If both above two properties set to true of false, it will show
both a spinner besides a calendar.
5. minDate : Set the optional minimum date in mm/dd/yyy
format.
6. maxDate : Set the maximum date to select, format is
mm/dd/yyyy.
7. startYear : Set optional start year.
8. endYear : Set optional end year.

Please Note : DatePicker’s init(int year, int month, int day,


OnDateChangedListener onDateChangedListener) method is a
very important method. This method can be used to initialize the
DatePicker displayed year, month and day. And the
onDateChangedListener object will listen to the user change date
event. When user choose another date, the listener’s
onDateChanged method will be invoked.
TimePicker Properties :
1. timePickerMode : Value can be spinner or clock. When set it’
value to clock, it will display a clock. When set is’s value to
spinner will display a spinner.
TimePicker Clock Mode

TimePicker Spinner Mode

2. headerBackground : This is a Color or Drawable resource id


which can be set to TimePicker’s header background.
3. is24HourView() : Check whether it is 24 hour time system.
4. setIs24HourView(boolean 24HourView) : Set if use 24 hour
time system.
5. getHour() : Get current hour integer value.
6. getMinute() : Get current minute integer value.
7. setOnTimeChangedListener() : Set call back listener when
time is changed.

3.
DatePicker TimePicker Examples :
There is a DatePicker and a TimePicker in this example. When you change
the date and time, the new date time will be shown in text view widget at
bottom.
Please Note : You can not change timezone in DatePicker. You can only
change timezone use java.util.Calendar class. And then get day info in that
timezone.

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<ScrollView 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:gravity="center_horizontal"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="8dp">

<TextView
android:id="@+id/tvShowDateTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Will display current date and time" />

<DatePicker
android:id="@+id/datePickerExample"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:calendarViewShown="false"
android:datePickerMode="spinner"
android:endYear="2100"
android:maxDate="12/31/2100"
android:minDate="01/01/2000"
android:spinnersShown="true"
android:startYear="2000" />

<TimePicker
android:id="@+id/timePickerExample"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:headerBackground="@color/colorBlue"
android:timePickerMode="clock" />

</LinearLayout>
</ScrollView>

MainActivity.java
package com.example.unit3;

import android.graphics.Color;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;

import androidx.appcompat.app.AppCompatActivity;

import java.util.Calendar;
import java.util.TimeZone;

public class MainActivity extends AppCompatActivity {

private int mYear;


private int mMonth;
private int mDay;
private int mHour;
private int mMinute;
private int mSeconds;

TextView textView;
DatePicker datePicker;
TimePicker timePicker;

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

initObject();

// Get current calendar date and time.


Calendar currCalendar = Calendar.getInstance();

// Set the timezone which you want to display time.


currCalendar.setTimeZone(TimeZone.getTimeZone("Asia/Kolkata"));

mYear = currCalendar.get(Calendar.YEAR);
mMonth = currCalendar.get(Calendar.MONTH);
mDay = currCalendar.get(Calendar.DAY_OF_MONTH);
mHour = currCalendar.get(Calendar.HOUR_OF_DAY);
mMinute = currCalendar.get(Calendar.MINUTE);
mSeconds = currCalendar.get(Calendar.SECOND);

showUserSelectDateTime();

// Get date picker object.


datePicker.init(mYear - 1, mMonth + 1, mDay + 5, new
DatePicker.OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker datePicker, int year, int month, int
day) {
mYear = year;
mMonth = month;
mDay = day;

showUserSelectDateTime();
}
});

// Get time picker object.


timePicker.setHour(this.mHour);
timePicker.setMinute(this.mMinute);

timePicker.setOnTimeChangedListener(new
TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker timePicker, int hour, int minute) {
mHour = hour;
mMinute = minute;

showUserSelectDateTime();
}
});

private void initObject() {


textView = (TextView) findViewById(R.id.tvShowDateTime);
datePicker = (DatePicker) findViewById(R.id.datePickerExample);
timePicker = (TimePicker) findViewById(R.id.timePickerExample);

textView.setTextColor(Color.BLUE);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(20);
}

/* Show user selected date time in bottom text vew area. */


private void showUserSelectDateTime() {
// Get TextView object which is used to show user pick date and time.

StringBuffer strBuffer = new StringBuffer();


strBuffer.append("You selected date time : ");
strBuffer.append(this.mYear);
strBuffer.append("-");
strBuffer.append(this.mMonth + 1);
strBuffer.append("-");
strBuffer.append(this.mDay);
strBuffer.append(" ");
strBuffer.append(this.mHour);
strBuffer.append(":");
strBuffer.append(this.mMinute);
strBuffer.append(":");
strBuffer.append(this.mSeconds);

textView.setText(strBuffer.toString());
}
}
Rating Bar and Progress Bar
Rating Bar
● Android RatingBar can be used to get the rating from the user. The
Rating returns a floating-point number. It may be 2.0, 3.5, 4.0 etc.
● Android RatingBar displays the rating in stars. Android RatingBar is
the subclass of AbsSeekBar class.
● The getRating() method of android RatingBar class returns the rating
number.

public class RatingBar

extends AbsSeekBar

Hiercharchy
java.lang.Object

↳ android.view.View

↳ android.widget.ProgressBar

↳ android.widget.AbsSeekBar

↳ android.widget.RatingBar

Nested classes

interface RatingBar.OnRatingBarChangeListener

A callback that notifies clients when the rating has been changed.
XML attributes

android:isIndicator Whether this rating bar is an indicator (and non-changeable by the


user).

android:numStars The number of stars (or rating items) to show.

android:rating The rating to set by default.

android:stepSize The step size of the rating.

Public methods

CharSequence getAccessibilityClassName()

Return the class name of this object to be used for accessibility


purposes.

int getNumStars()

Returns the number of stars shown.

RatingBar.OnRating getOnRatingBarChangeListener()
BarChangeListener

float getRating()

Gets the current rating (number of stars filled).

float getStepSize()

Gets the step size of this rating bar.


boolean isIndicator()

void setIsIndicator(boolean isIndicator)

Whether this rating bar should only be an indicator (thus


non-changeable by the user).

void setMax(int max)

Set the upper range of the progress bar max.

void setNumStars(int numStars)

Sets the number of stars to show.

void setOnRatingBarChangeListener(RatingBar.OnRatingBarC
hangeListenerlistener)

Sets the listener to be called when the rating changes.

void setRating(float rating)

Sets the rating (the number of stars filled).

void setStepSize(float stepSize)

Sets the step size (granularity) of this rating bar.


Android RatingBar Example
Let's see the simple example of rating bar in android.

activity_main.xml
Drag the RatingBar and Button from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml

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


2. <androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
3. xmlns:app="http://schemas.android.com/apk/res-auto"
4. xmlns:tools="http://schemas.android.com/tools"
5. android:layout_width="match_parent"
6. android:layout_height="match_parent"
7. tools:context=".MainActivity">
8.

9. <Button
10. android:id="@+id/btnSubmit"
11. android:layout_width="wrap_content"
12. android:layout_height="wrap_content"
13. android:text="Submit"
14. app:layout_constraintBottom_toBottomOf="parent"
15. app:layout_constraintLeft_toLeftOf="parent"
16. app:layout_constraintRight_toRightOf="parent"
17. app:layout_constraintTop_toBottomOf="@+id/ratingBar" />
18.

19. <RatingBar
20. android:id="@+id/ratingBar"
21. android:layout_width="wrap_content"
22. android:layout_height="wrap_content"
23. android:layout_marginTop="300dp"
24. android:stepSize="0.5"
25. app:layout_constraintEnd_toEndOf="parent"
26. app:layout_constraintHorizontal_bias="0.50"
27. app:layout_constraintStart_toStartOf="parent"
28. app:layout_constraintTop_toTopOf="parent" />
29.

30. </androidx.constraintlayout.widget.ConstraintLayout>

Activity class
Let's write the code to display the rating of the user.
File: MainActivity.java

1. package com.example.unit3;

2.

3. import android.os.Bundle;

4. import android.view.View;

5. import android.widget.Button;

6. import android.widget.RatingBar;

7. import android.widget.Toast;

8.

9. import androidx.appcompat.app.AppCompatActivity;

10.

11. import com.example.mytoastandsnackbar.R;

12.

13. public class MainActivity extends AppCompatActivity {

14. RatingBar ratingbar;


15. Button button;
16.
17. @Override
18. protected void onCreate(Bundle savedInstanceState) {
19. super.onCreate(savedInstanceState);
20. setContentView(R.layout.activity_main);
21.

22. initObject();
23. addListeners();
24. }
25.

26. private void initObject() {


27. ratingbar = (RatingBar) findViewById(R.id.ratingBar);
28. button = (Button) findViewById(R.id.btnSubmit);
29. }
30.

31. private void addListeners() {


32. //Performing action on Button Click
33. button.setOnClickListener(new View.OnClickListener() {
34. @Override
35. public void onClick(View arg0) {
36. //Getting the rating and displaying it on the toast
37. String rating = "" + ratingbar.getRating();
38. Toast.makeText(getApplicationContext(), rating,
Toast.LENGTH_LONG).show();
39. }
40.

41. });
42. }
43. }
Output:
Progress Bar
● A user interface element that indicates the progress of an operation.
● Progress bar supports two modes to represent progress: determinate, and
indeterminate.
● For a visual overview of the difference between determinate and indeterminate
progress modes, see Progress & activity.
● Display progress bars to a user in a non-interruptive way. Show the progress bar
in your app's user interface or in a notification instead of within a dialog.

Indeterminate Progress

Use indeterminate mode for the progress bar when you do not know how long an
operation will take. Indeterminate mode is the default for progress bar and shows a
cyclic animation without a specific amount of progress indicated. The following
example shows an indeterminate progress bar:

<ProgressBar
android:id="@+id/indeterminateBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

Determinate Progress

Use determinate mode for the progress bar when you want to show that a specific
quantity of progress has occurred. For example, the percent remaining of a file being
retrieved, the amount records in a batch written to database, or the percent remaining of
an audio file that is playing.

To indicate determinate progress, you set the style of the progress bar
toR.style.Widget_ProgressBar_Horizontal and set the amount of progress. The
following example shows a determinate progress bar that is 25% complete:
<ProgressBar
android:id="@+id/determinateBar"
style="@android:style/Widget.ProgressBar.Horizontal"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:progress="25"/>

● You can update the percentage of progress displayed by using the


setProgress(int) method, or by calling incrementProgressBy(int) to
increase the current progress completed by a specified amount. By default, the
progress bar is full when the progress value reaches 100.
● You can adjust this default by setting the android:maxattribute.

Other progress bar styles provided by the system include:

● Widget.ProgressBar.Horizontal
● Widget.ProgressBar.Small
● Widget.ProgressBar.Large
● Widget.ProgressBar.Inverse
● Widget.ProgressBar.Small.Inverse
● Widget.ProgressBar.Large.Inverse

The "inverse" styles provide an inverse color scheme for the spinner, which may be
necessary if your application uses a light colored theme (a white background).

XML attributes

android:animationResolu Timeout between frames of animation in milliseconds.


tion

android:indeterminate Allows to enable the indeterminate mode.


android:indeterminateBe Defines how the indeterminate mode should behave when the
havior progress reaches max.

android:indeterminateDr Drawable used for the indeterminate mode.


awable

android:indeterminateDu Duration of the indeterminate animation.


ration

android:indeterminateOn Restricts to ONLY indeterminate mode (state-keeping progress


ly mode will not work).

android:indeterminateTi Tint to apply to the indeterminate progress indicator.


nt

android:indeterminateTi Blending mode used to apply the indeterminate progress


ntMode indicator tint.

android:interpolator Sets the acceleration curve for the indeterminate animation.

android:max Defines the maximum value.

android:maxHeight An optional argument to supply a maximum height for this view.

android:maxWidth An optional argument to supply a maximum width for this view.

android:min Defines the minimum value.

android:minHeight
android:minWidth

android:mirrorForRtl Defines if the associated drawables need to be mirrored when


in RTL mode.

android:progress Defines the default progress value, between 0 and max.

android:progressBackgro Tint to apply to the progress indicator background.


undTint

android:progressBackgro Blending mode used to apply the progress indicator background


undTintMode tint.

android:progressDrawabl Drawable used for the progress mode.


e

android:progressTint Tint to apply to the progress indicator.

android:progressTintMod Blending mode used to apply the progress indicator tint.


e

android:secondaryProgre Defines the secondary progress value, between 0 and max.


ss

android:secondaryProgre Tint to apply to the secondary progress indicator.


ssTint

android:secondaryProgre Blending mode used to apply the secondary progress indicator


ssTintMode tint.
File Download
Refer Link :
https://www.androidhive.info/2012/04/android-downloading-file-by-showin
g-progress-bar/

You might also like