Professional Documents
Culture Documents
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
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
Method Description
public static Toast makeText(Context context, CharSequence text, int makes the toast containing text and duration.
duration)
public void setMargin (float horizontalMargin, float verticalMargin) changes the horizontal and vertical margin
difference.
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
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);
:
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
1. LENGTH_INDEFINITE
2. LENGTH_LONG
3. LENGTH_SHORT
// 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 :
● 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();
● 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):
<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
toast.show();
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;
toast.show();
}
}
Output :
Button
a. Toggle Button
b. Switch Button
c. Image Button
d. Radio Button
Toggle Button
Method Description
<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;
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.
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>
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.
Attribute Description
android:gravity It is used to specify how to align the text like left, right,
center, top, etc.
android:padding It is used to set the padding from left, right, top and
bottom.
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;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initObjects();
addListeners();
}
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();
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: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
@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();
}
});
}
}
<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>
<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.
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" />
<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" />
<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;
}
}
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
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
<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>
<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.
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.
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
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;
@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();
}
});
}
}
<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>
<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
<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;
@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 ?");
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;
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
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
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;
TextView textView;
DatePicker datePicker;
TimePicker timePicker;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initObject();
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();
showUserSelectDateTime();
}
});
timePicker.setOnTimeChangedListener(new
TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker timePicker, int hour, int minute) {
mHour = hour;
mMinute = minute;
showUserSelectDateTime();
}
});
textView.setTextColor(Color.BLUE);
textView.setGravity(Gravity.CENTER);
textView.setTextSize(20);
}
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.
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
Public methods
CharSequence getAccessibilityClassName()
int getNumStars()
RatingBar.OnRating getOnRatingBarChangeListener()
BarChangeListener
float getRating()
float getStepSize()
void setOnRatingBarChangeListener(RatingBar.OnRatingBarC
hangeListenerlistener)
activity_main.xml
Drag the RatingBar and Button from the pallete, now the activity_main.xml file will like this:
File: activity_main.xml
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.
12.
22. initObject();
23. addListeners();
24. }
25.
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"/>
● 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:minHeight
android:minWidth