Unit 3 Exploring User Interface Screen Elements

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

Unit: 3 Exploring User Interface Screen Elements

3.1 Introducing Android Views, Layouts, TextView, Buttons, Check Boxes, Radio Groups, Indicators, SeekBar,
Context Menus, User Events, Styles and Themes, Dates and Times, Retrieving Data.

What is Android Views?

A View is a simple building block of a user interface. It is a small rectangular box that can be TextView,
EditText, or even a button. It occupies the area on the screen in a rectangular area and is responsible for drawing
and event handling. View is a superclass of all the graphical user interface components.

The Android SDK has a Java package name android.view. This package contains a number of interfaces and
classes related to drawing on the screen. However, when we refer to the View object, we actually refer to onl y
one of the classes within this package: the android.view.View class.

View is the basic building block of UI (User Interface) in android. View refers to the android.view.View class,
which is the super class for all the GUI components like TextView, ImageView, Button etc. View class extends
Object class and Implements Drawable.Callback, KeyEvent.Callback and AccessibilityEventSource.

The question that might be bothering you would be, what can be the size of this rectangle?

The answer is either we can set it manually, by specifying the exact size (with proper units) or by using some
predefined values. These predefined values are match_parent and wrap_content. match_parent means it will
occupy the complete space available on the display of the device. Whereas, wrap_content means it will occupy
only that much space as required for its content to display.

ViewGroup

View Group is a subclass of the ViewClass and can be considered as a superclass of Layouts. It provides an
invisible co0ntainer to hold the views or layouts. ViewGroup instances and views work together as a container
for Layouts. To understand in simpler words it can be understood as a special view that can hold other views
that are often known as a child view.

Unit-3 Exploring User Interface Screen Elements Page 1


The Android framework will allow us to use UI elements or widgets in two ways:

 Use UI elements in the XML file


 Create elements in the Kotlin file dynamically

Introducing Android Layouts

A layout defines the structure for a user interface in your app, such as in an activity. All elements in the layout
are built using a hierarchy of View and ViewGroup objects. A View usually draws something the user can see
and interact with. Whereas a ViewGroup is an invisible container that defines the layout structure for View and
other ViewGroup objects.

One special type of control found within the android.widget package is called a layout. A layout control is still a
View object, but it doesn’t actually draw anything specific on the screen. Instead, it is a parent container for
organizing other controls (children). Layout controls determine how and where on the screen child controls are
drawn. Each type of layout control draws its children using particular rules. For instance, the LinearLayout
control draws its child controls in a single horizontal row or a single vertical column. Similarly, a TableLayout
control displays each child control in tabular format(in cells within specific rows and columns).

In “Designing User Interfaces with Layouts,” we organize various controls within layouts and other containers.
These special View controls, which are derived from the android.view.ViewGroup class, are useful only after
you understand the various display controls these containers can hold. By necessity, we use some of the layout
View objects within this chapter to illustrate how to use the controls previously mentioned.

Types of Layouts

 Linear Layout
 Relative Layout
 Constraint Layout
 Table Layout
 Frame Layout
 List View
 Grid View
 Absolute Layout
 WebView
 ScrollView
 Android Linear Layout: LinearLayout is a ViewGroup subclass, used to provide child View elements
one by one either in a particular direction either horizontally or vertically based on the orientation
property.
 Android Relative Layout: RelativeLayout is a ViewGroup subclass, used to specify the position of
child View elements relative to each other like (A to the right of B) or relative to the parent (fix to the
top of the parent).

Unit-3 Exploring User Interface Screen Elements Page 2


 Android Constraint Layout: ConstraintLayout is a ViewGroup subclass, used to specify the position
of layout constraints for every child View relative to other views present. A ConstraintLayout is similar
to a RelativeLayout, but having more power.
 Android Frame Layout: FrameLayout is a ViewGroup subclass, used to specify the position of View
elements it contains on the top of each other to display only a single View inside the FrameLayout.
 Android Table Layout: TableLayout is a ViewGroup subclass, used to display the child View
elements in rows and columns.
 Android Web View: WebView is a browser that is used to display the web pages in our activity
layout.
 Android ListView: ListView is a ViewGroup, used to display scrollable lists of items in a single
column.
 Android Grid View: GridView is a ViewGroup that is used to display a scrollable list of items in a
grid view of rows and columns.

Layout params

This tutorial is more about creating your GUI based on layouts defined in XML file. A layout may contain any
type of widgets such as buttons, labels, textboxes, and so on. Following is a simple example of XML file having
LinearLayout −

Once your layout has created, you can load the layout resource from your application code, in your
Activity.onCreate() callback implementation as shown below −

Unit-3 Exploring User Interface Screen Elements Page 3


Attributes of Layout in Android

The following are the attributes for customizing a Layout while defining it:

 android:id: It uniquely identifies the Android Layout.


 android:hint: It shows the hint of what to fill inside the EditText.
 android:layout_height: It sets the height of the layout.
 android:layout_width: It sets the width of the layout.
 android:layout_gravity: It sets the position of the child view.
 android:layout_marginTop: It sets the margin of the from the top of the layout.
 android:layout_marginBottom: It sets the margin of the from the bottom of the layout.
 android:layout_marginLeft: It sets the margin of the from the left of the layout.
 android:layout_marginRight: It sets the margin of the from the right of the layout.
 android:layout_x: It specifies the x coordinates of the layout.
 android:layout_y: It specifies the y coordinates of the layout.

Types of Android Views(Control,palette)

Another thing that might now come to your mind must be, “what are the available types of view in Android that
we can use?”
For that, we’ll see all these types one by one as follows:

 TextView
 EditText
 Button
 Image Button
 Date Picker
 RadioButton
 CheckBox buttons
 Image View

Unit-3 Exploring User Interface Screen Elements Page 4


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

Attribute & Description


android:id This is the ID which uniquely identifies the control.
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

android:cursorVisible Makes the cursor visible (the default) or invisible. Default is false.
android:editable If set to true, specifies that this TextView has an input method.
android:fontFamily Font family (named by string) for the text.
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.
android:hint Hint text to display when the text is empty.
android:inputType The type of data being placed in a text field. Phone, Date, Time, Number, Password
etc.
android:password Whether the characters of the field are displayed as password dots instead of
themselves. Possible value either "true" or "false".
android:phoneNumber If set, specifies that this TextView has a phone number input method. Possible value
either "true" or "false".
android:text Text to display.
android:textAllCaps Present the text in ALL CAPS. Possible value either "true" or "false".
android:textSize Size of the text. Recommended dimension type for text is "sp" for scaled-pixels
(example: 15sp).

Example

MainActivity.java

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

Unit-3 Exploring User Interface Screen Elements Page 5


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>

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

Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text.
android:editable If set, specifies that this TextView has an input method.
android:text This is the Text to display.

Unit-3 Exploring User Interface Screen Elements Page 6


Inherited from android.view.View Class –

Attribute Description
android:background This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view.
android:onClick This is the name of the method in this View's context to invoke
when the view is clicked.
android:visibility This controls the initial visibility of the view.

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

MainActivity.java file-

package com.example.demo;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;

Unit-3 Exploring User Interface Screen Elements Page 7


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

3).Button:-
A Button is a Push-button which can be pressed, or clicked, by the user to perform an action.

Button Attributes

Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text.
android:editable If set, specifies that this TextView has an input method.
android:text This is the Text to display

Inherited from android.view.View Class –


android:background This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.

Unit-3 Exploring User Interface Screen Elements Page 8


android:id This supplies an identifier name for this view.
android:onClick This is the name of the method in this View's context to invoke when
the view is clicked.
android:visibility This controls the initial visibility of the view.

Button Example

Activity_main.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentEnd="true"
android:layout_centerInParent="true"
android:layout_marginStart="172dp"
android:layout_marginEnd="151dp"
android:text="NEXT"
tools:layout_editor_absoluteX="149dp"
tools:layout_editor_absoluteY="80dp"
android:onClick="btn_next"/>
<Button
android:id="@+id/btn_previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn_next"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginTop="67dp"
android:layout_marginEnd="140dp"
android:layout_marginBottom="225dp"
android:text="PREVIOUS"
android:onClick="btn_previous"/>
</RelativeLayout>

MainActivity.java

package com.example.exampleofbutton;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void btn_next(View view) {
Toast.makeText(this,"Next Button Clicked", Toast.LENGTH_SHORT).show();
}

Unit-3 Exploring User Interface Screen Elements Page 9


public void btn_previous(View view) {
Toast.makeText(this,"Previous Button Clicked", Toast.LENGTH_SHORT).show();
}
}

Example of TextView,EditText and Button

Activity_main.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/parentRelative"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
tools:context=".MainActivity">

<EditText
android:id="@+id/editTextName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textviewname"
android:layout_marginTop="-249dp"
android:ems="10"
android:hint="Enter Your Name"
android:inputType="textPersonName"
android:padding="20dp"
android:textColor="#F44336" />

<Button
android:id="@+id/btnclickhere"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/editTextName"
android:layout_marginTop="29dp"
android:padding="20dp"
android:text="ClickMe" />
<TextView
android:id="@+id/textviewname"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:text="TextView" />
</RelativeLayout>

MainActivity.java

package com.example.exampleoftextview;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

Unit-3 Exploring User Interface Screen Elements Page 10


EditText editTextName;
Button btnclickhere;
TextView textviewname;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextName=(EditText)findViewById(R.id.editTextName);
btnclickhere=(Button)findViewById(R.id.btnclickhere);
textviewname=(TextView)findViewById(R.id.textviewname);
btnclickhere.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name=editTextName.getText().toString();
textviewname.setText("Hi"+name);

}
});
}
}

4). CheckBox:- Android CheckBox is a type of two state button either checked or unchecked.There can be
a lot of usage of checkboxes. For example, it can be used to know the hobby of the user, activate/deactivate
the specific action etc.Android CheckBox class is the subclass of CompoundButton class.

The android.widget.CheckBox class provides the facility of creating the CheckBoxes.

Method:-There are many inherited methods of View, TextView, and Button classes in the CheckBox class.
Some of them are as follows:

1).public boolean isChecked():-Returns true if it is checked otherwise false.

2).public void setChecked(boolean status):- Changes the state of the CheckBox.

CheckBox Attributes

Unit-3 Exploring User Interface Screen Elements Page 11


Attribute Description
android:autoText If set, specifies that this TextView has a textual input method and
automatically corrects some common spelling errors.
android:drawableBottom This is the drawable to be drawn below the text.
android:drawableRight This is the drawable to be drawn to the right of the text.
android:editable If set, specifies that this TextView has an input method.
android:text This is the Text to display
Inherited from android.view.View Class –
android:background This is a drawable to use as the background.
android:contentDescription This defines text that briefly describes content of the view.
android:id This supplies an identifier name for this view.
android:onClick This is the name of the method in this View's context to invoke when
the view is clicked.
android:visibility This controls the initial visibility of the view.

Example

MainActivity.java

package com.example.checkboxexample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
CheckBox ch,ch1,ch2,ch3;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ch=(CheckBox)findViewById(R.id.checkBox);
ch1=(CheckBox)findViewById(R.id.checkBox3);
ch2=(CheckBox)findViewById(R.id.checkBox4);
ch3=(CheckBox)findViewById(R.id.checkBox5);
}
// This function is invoked when the button is pressed.
public void Check(View view) {
/* Finding CheckBox by its unique ID */
String msg="";
// Concatenation of the checked options in if
// isChecked() is used to check whether
// the CheckBox is in true state or not.
if(ch.isChecked())
msg = msg + " Painting ";
if(ch1.isChecked())
msg = msg + " Dancing ";
if(ch2.isChecked())
msg = msg + " Reading ";
if(ch3.isChecked())
msg = msg + " Surfing ";
// Toast is created to display the
// message using show() method.
Toast.makeText(this, msg+"Are Selected", Toast.LENGTH_LONG).show();
}
}

Unit-3 Exploring User Interface Screen Elements Page 12


activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<TextView
android:layout_width="398dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="48dp"
android:layout_marginEnd="8dp"
android:text="Choose your hobbies:"
android:textSize="24sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<CheckBox
android:id="@+id/checkBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="Painting"
android:textSize="18sp" />
<CheckBox
android:id="@+id/checkBox3"
android:layout_width="match_parent"
android:layout_height="37dp"
android:text="Dancing"
android:textSize="18sp" />
<CheckBox
android:id="@+id/checkBox4"
android:layout_width="match_parent"
android:layout_height="37dp"
android:text="Reading"
android:textSize="18sp" />
<CheckBox
android:id="@+id/checkBox5"
android:layout_width="match_parent"
android:layout_height="37dp"
android:text="Surfing"
android:textSize="18sp" />
<Button
android:id="@+id/button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:onClick="Check"
android:text="@string/submit"/>
</LinearLayout>

Unit-3 Exploring User Interface Screen Elements Page 13


5).Radio Group and 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

Activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical" >

<TextView
android:id="@+id/textView"
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"

Unit-3 Exploring User Interface Screen Elements Page 14


android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="B.Com"
android:layout_marginTop="20dp"
android:textSize="20dp" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B.C.A"
android:layout_marginTop="10dp"
android:textSize="20dp" />
<RadioButton
android:id="@+id/radioButton3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="B.B.A"
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"

Unit-3 Exploring User Interface Screen Elements Page 15


android:onClick="onclickbuttonMethod"
android:layout_gravity="center_horizontal" />
</LinearLayout>

MainActivity.java

package com.example.radiobuttondemo;
import androidx.appcompat.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 btn;
RadioButton genderradioButton;
RadioGroup rGroup;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rGroup=(RadioGroup)findViewById(R.id.radioGroup);
}
public void onclickbuttonMethod(View view) {
int selectedId = rGroup.getCheckedRadioButtonId();
genderradioButton = (RadioButton) findViewById(selectedId);
// Toast.makeText(this, "genderradioButton", Toast.LENGTH_SHORT).show();
if(selectedId==-1) {
Toast.makeText(MainActivity.this,"Nothing selected", Toast.LENGTH_SHORT).show();
} else{
Toast.makeText(MainActivity.this,genderradioButton.getText(),
Toast.LENGTH_SHORT).show();
}
}
}

Indicators
The Android SDK provides a number of controls that can be used to visually show some form of
information to the user. These indicator controls include progress bars, clocks, and other similar controls.
ProgressBars
Android ProgressBar is a graphical view indicator that shows some progress. Android progress bar displays

Unit-3 Exploring User Interface Screen Elements Page 16


a bar representing the completing of the task. Progress bar in android is useful since it gives the user an idea
of time to finish its task.
Progress bars are used to show progress of a task. For example, when you are uploading or downloading
something from the internet, it is better to show the progress of download/upload to the user.

Android ProgressBar attributes

Some important attributes used to describe a ProgressBar are given below.

 android:max : We can set the maximum value of the ProgressBar using this attribute. By default
the progress bar maximum value is 100
 android:indeterminate : A boolean value is set depending on whether the time is determinate or
not. Setting this attribute to false would show the actual progress. Else if it’s set to true a cyclic
animation is displayed to show that progress is happening
 android:minHeight : It’s used to set the height of the ProgressBar
 android:minWidth : It’s used to set the width of the ProgressBar
 android:progress : It’s used to set the number by which the progress bar value will be
incremented
 style : By default the progress bar will be displayed as a spinning wheel. If we want it to be
displayed as a horizontal bar, we need to set the attribute as :
style=”?android:attr/progressBarStyleHorizontal”

Method

1).getMax():-This method returns the maximum value of the progress.

2). incrementProgressBy(int diff):-This method increments the progress bar by the difference of value
passed as a parameter.

3). setIndeterminate(boolean indeterminate):-This method sets the progress indicator as determinate or


indeterminate.

4). setMax(int max):-This method sets the maximum value of the progress dialog.

5). setProgress(int value):-This method is used to update the progress dialog with some specific value.

6). show(Context context, CharSequence title, CharSequence message):-This is a static method, used to
display progress dialog.

Example

Activity_main.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ProgressBar
android:id="@+id/simpleProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:layout_centerHorizontal="true"/>
<Button

Unit-3 Exploring User Interface Screen Elements Page 17


android:id="@+id/startButton"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:text="Start"
android:textSize="20sp"
android:textStyle="bold"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp"
android:padding="10dp"
android:background="#0f0"
android:textColor="#fff"/>
</RelativeLayout>

Mainactivity.java

package com.example.textviewdemo;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate progress bar and start button
final ProgressBar simpleProgressBar = (ProgressBar) findViewById(R.id.simpleProgressBar);
Button startButton = (Button) findViewById(R.id.startButton);
// perform click event on button
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// visible the progress bar
simpleProgressBar.setVisibility(View.VISIBLE);
}
});
}
}

Unit-3 Exploring User Interface Screen Elements Page 18


SeekBar:-

Android SeekBar is a type of ProgressBar. On touching the thumb on seekbar and dragging it to the right
or left, the current value of the progress changes. SeekBar is used for forwarding or backwarding the songs,
Video etc. In the setOnSeekBarChangeListener interface is used which provides three methods.

 onProgressChanged: In this method progress is changed and then according to this change the
progress value can used in our logic.
 onStartTrackingTouch: In this method when the user has started dragging, then this method will
be called automatically.
 onStopTrackingTouch: In this method, when the user stops dragging, then this method will
called automatically.

Example

Activity_main.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="180dp"
android:layout_marginBottom="460dp"
android:text="Example of Seekbar" />

<SeekBar
android:id="@+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="372dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:background="#0F0"/><!-- set green color in the background of seek bar-->
</RelativeLayout>

MainActivity.java

package com.example.seekbarexample;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {

Unit-3 Exploring User Interface Screen Elements Page 19


// Define the global variable
SeekBar seekbar;
TextView Text_message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// use findViewById() to get the Button
Text_message= (TextView)findViewById(R.id.textView);
seekbar= (SeekBar)findViewById(R.id.seekBar);
//SeekBar.setBackgroundColor(Color.GREEN);
seekbar.setBackgroundColor(Color.GREEN);// green background color for the seek bar
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
Toast.makeText(getApplicationContext(),"seekbar progress: "+progress,
Toast.LENGTH_SHORT).show();
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"seekbar touch started!",
Toast.LENGTH_SHORT).show();
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Toast.makeText(getApplicationContext(),"seekbar touch stopped!",
Toast.LENGTH_SHORT).show();
}
});
}
}

Context menus:-
In Android, the context menu is like a floating menu and arises when the user has long
pressed or clicks on an item and is beneficial for implementing functions that define the specific content or
reference frame effect. The Android context menu is similar to the right-click menu in Windows or Linux.
In the Android system, the context menu provides actions that change a specific element or context frame in
the user interface and one can provide a context menu for any view. The context menu will not support any
object shortcuts and object icons. Note that we are going to implement this project using the Java language.

Example
Step 1: Create a New Project
Step 2: Working with the activity_main.xml file Open res -> Layout -> activity_main.xml and write the
following code. In this file add only a TextView to display a simple text.

Activity_main.xml

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


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"

Unit-3 Exploring User Interface Screen Elements Page 20


android:layout_marginTop="20dp"
android:text="Long press me!"
android:textColor="#000"
android:textSize="20sp"
android:textStyle="bold" />
</RelativeLayout>

Step 3: Working with the Mainactivity.java file Open the app -> Java -> Package -> Mainactivity.java file.
In this step, add the code to show the ContextMenu. Whenever the app will start make a long click on a text
and display the number of options to select them for specific purposes.

MainActivity.java

package com.example.contextmenuexample;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView textView;
RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Link those objects with their respective id's
// that we have given in .XML file
textView = (TextView) findViewById(R.id.textView);
relativeLayout = (RelativeLayout) findViewById(R.id.relLayout);
// here you have to register a view for context menu
// you can register any view like listview, image view,
// textview, button etc
registerForContextMenu(textView);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// you can set menu header with title icon etc
menu.setHeaderTitle("Choose a color");
// add menu items
menu.add(0, v.getId(), 0, "Yellow");
menu.add(0, v.getId(), 0, "Gray");
menu.add(0, v.getId(), 0, "Cyan");
}
// menu item select listener
@Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Yellow") {
relativeLayout.setBackgroundColor(Color.YELLOW);
} else if (item.getTitle() == "Gray") {
relativeLayout.setBackgroundColor(Color.GRAY);
} else if (item.getTitle() == "Cyan") {
relativeLayout.setBackgroundColor(Color.CYAN);
}
return true;

Unit-3 Exploring User Interface Screen Elements Page 21


}
}

User Event

Events are a useful way to collect data about a user's interaction with interactive components of
Applications. Like button presses or screen touch etc. The Android framework maintains an event queue as
a first-in, first-out (FIFO) basis. You can capture these events in your program and take appropriate action
as per requirements.

There are following three concepts related to Android Event Management –


● Event Listeners − An event listener is an interface in the View class that contains a single callback
method. These methods will be called by the Android framework when the View to which the listener has
been registered is triggered by user interaction with the item in the UI.
● Event Listeners Registration − Event Registration is the process by which an Event Handler gets
registered with an Event Listener so that the handler is called when the Event Listener fires the event.
● Event Handlers − When an event happens and we have registered an event listener for the event, the
event listener calls the Event Handlers, which is the method that actually handles the event.
Event Listeners & Event Handlers
Event Handler Event Listener & Description
onClick() OnClickListener()
This is called when the user either clicks or touches or focuses upon
any widget like button, text, image etc. You will use onClick() event
handler to handle such event.
onLongClick() OnLongClickListener()
This is called when the user either clicks or touches or focuses upon
any widget like button, text, image etc. for one or more seconds. You
will use onLongClick() event handler to handle such event.
onFocusChange() OnFocusChangeListener()
This is called when the widget loses its focus ie. user goes away from
the view item. You will use the onFocusChange() event handler to
handle such an event.
onKey() OnFocusChangeListener()
This is called when the user is focused on the item and presses or
releases a hardware key on the device. You will use onKey() event
handler to handle such an event.
onTouch() OnTouchListener()
This is called when the user presses the key, releases the key, or any
movement gesture on the screen. You will use onTouch() event handler
to handle such event.
onMenuItemClick() OnMenuItemClickListener()
This is called when the user selects a menu item. You will use
onMenuItemClick() event handler to handle such event.
onCreateContextMenu() onCreateContextMenuItemListener()
This is called when the context menu is being built(as the result of a
sustained "long click)

Unit-3 Exploring User Interface Screen Elements Page 22


Event Listeners Registration
Event Registration is the process by which an Event Handler gets registered with an Event
Listener so that the handler is called when the Event Listener fires the event. Though there are several
tricky ways to register your event listener for any event, I'm going to list down only top 3 ways, out of
which you can use any of them based on the situation.
● Using an Anonymous Inner Class
● Activity class implements the Listener interface.
● Using Layout file activity_main.xml to specify event handler directly.

Touch Mode
Users can interact with their devices by using hardware keys or buttons or touching the
screen.Touching the screen puts the device into touch mode. The user can then interact with it by touching
the on-screen virtual buttons, images, etc.You can check if the device is in touch mode by calling the View
class's InTouchMode() method.

Focus
A view or widget is usually highlighted or displays a flashing cursor when it’s in focus. This
indicates that it’s ready to accept input from the user.
● isFocusable() − it returns true or false
● isFocusableInTouchMode() − checks to see if the view is focusable in touch mode. (A view may be
focusable when using a hardware key but not when the device is in touch mode)

android:foucsUp="@=id/button_l"

onTouchEvent()

public boolean onTouchEvent(motionEvent event){


switch(event.getAction()){
case TOUCH_DOWN:
Toast.makeText(this,"you have clicked down Touch button",Toast.LENTH_LONG).show();
break();

case TOUCH_UP:
Toast.makeText(this,"you have clicked up touch button",Toast.LENTH_LONG).show();
break;

case TOUCH_MOVE:
Toast.makeText(this,"you have clicked move touch button"Toast.LENTH_LONG).show();
break;
}
return super.onTouchEvent(event) ;
}

Android Input Events Example

Activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="@+id/btnClick"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Event"
android:layout_marginTop="200dp" android:layout_marginLeft="130dp"/>
<TextView

Unit-3 Exploring User Interface Screen Elements Page 23


android:id="@+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:textColor="#86AD33"
android:textSize="20dp"
android:textStyle="bold"
android:layout_marginTop="12dp"/>
</LinearLayout>

MainActivity.java

package com.tutlane.inputeventsexample;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {


Button btn;
TextView tView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.btnClick);
tView = (TextView)findViewById(R.id.txtResult);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tView.setText("You Clicked On Button");
}
});
}
}

Styles and Themes

A style resource defines the format and looks for a UI. A style can be applied to an individual View
(from within a layout file) or to an entire Activity or application (from within the manifest file).

Defining Styles

A style is defined in an XML resource that is separate from the XML that specifies the layout. This XML
file resides under the res/values/ directory of your project and will have as the root node which is
mandatory for the style file. The name of the XML file is arbitrary, but it must use the .xml extension.

You can define multiple styles per file using tag as shown below –

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


<resources>
<style name="CustomFontStyle">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:capitalize">characters</item>
<item name="android:typeface">monospace</item>
<item name="android:textSize">12pt</item>

Unit-3 Exploring User Interface Screen Elements Page 24


<item name="android:textColor">#00FF00</item>/>
</style>
</resources>

Using Styles Once your style is defined, you can use it in your XML Layout file using style attribute as
follows –

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


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

<TextView
android:id="@+id/text_id"
style="@style/CustomFontStyle"
android:text="@string/hello_world" />

</LinearLayout>

Android Themes

Theme is a style that is applied to an entire activity or app, instead of an individual View like as mentioned
above. When we applied a style as a theme, the views in activity or app apply to the all style attributes that
supports. For example. If we apply TextviewStyle as a theme for an activity, then the text of all
the views in activity appears in the same style.

Following is the example of defining a theme in the android application.

<color name="custom_theme_color">#b0b0ff</color>
<style name="CustomTheme" parent="Theme.AppCompat.Light">
<item name="android:windowBackground">@color/custom_theme_color</item>
<item name="android:colorBackground">@color/custom_theme_color</item>
</style>

The above code overrides windowBackground and colorBackground properties of


Theme.AppCompat.Light theme.

To set a theme for a particular activity, open AndroidManifest.xml file and write the code like as shown
below

<activity android:theme="@android:style/CustomTheme">

In case, if we want to set the theme for all the activities in android application, open AndroidManifest.xml
file and write the code like as shown below.

<application android:theme="@android:style/CustomTheme">

Android Styling Color Palette

In android, we can customize the application basic theme colors based on our requirements.

Following is the example of basic material design in the android application.

Unit-3 Exploring User Interface Screen Elements Page 25


Generally, the above layout defined in styles.xml file like as shown below and it resides in res/values
folder.

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">


<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>

We can customize the application basic theme colors based on our requirements. Now we will see how to
use these styles and themes in android applications with examples.

Android Styles and Themes Example

Following is the example of defining a custom style for controls in LinearLayout to apply different styles
for controls in the android application.

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

Now we need to define our styles in styles.xml file, for that open styles.xml file from \res\values folder
and write the code like as shown below.

styles.xml

<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<style name="TextviewStyle" parent="@android:style/Widget.TextView">
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">100dp</item>
<item name="android:layout_marginTop">10dp</item>

Unit-3 Exploring User Interface Screen Elements Page 26


<item name="android:textColor">#86AD33</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">20dp</item>
</style>
<style name="ButtonStyle" parent="@android:style/Widget.Button">
<item name="android:layout_width">200dp</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">100dp</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:textColor">#FFFFFF</item>
<item name="android:background">#F1511B</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">15dp</item>
</style>
<string name="wlcmsg">welcome </string>
</resources>

If you observe above code, we defined a two styles (TextViewStyle, ButtonStyle) and we can apply these
styles for required controls in android application.

Now open an activity_main.xml file from \res\layout path and write the code like as shown below

activity_main.xml

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


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="200dp"
android:textColor="#00ADEF"
android:textSize="15dp"
android:text="@string/wlcmsg"/>
<TextView
android:id="@+id/TextView2"
style="@style/TextviewStyle"
android:text="Welcome to Tutlane"/>
<Button
android:id="@+id/btnShow"
android:text="Click on Button"
style="@style/ButtonStyle" />
</LinearLayout>

If you observe above code we are referring our styles to required controls using style attribute.

Dates and Times

Date and Time in Android are formatted using the SimpleDateFormat library from Java, using Calendar
instance which helps to get the current system date and time. The current date and time are of the type Long
which can be converted to a human-readable date and time. In this article, it’s been discussed how the Date
and Time values can be formatted in various formats and displayed. Have a look at the following image to
get an idea of the entire discussion.

Unit-3 Exploring User Interface Screen Elements Page 27


Steps to Format the Date and Time in Android

Step 1: Create an empty activity project

 Using Android Studio create an empty activity project. Refer to Android | How to Create/Start a
New Project in Android Studio?

Step 2: Working with the activity_main.xml file

 The main layout of the activity file containing 8 TextViews. One to show the current system date
and time value in Long type, and others to display the same date and time value in a formatted
human-readable way.
 To implement the UI invoke the following code inside the activity_main.xml file.

Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="HardcodedText">

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="32dp"
android:text="Date and Time value in Long type :"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

Unit-3 Exploring User Interface Screen Elements Page 28


<!--text view to show the current
date and time in Long type-->
<TextView
android:id="@+id/dateTimeLongValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="64dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="64dp"
android:text="Date and Time formatted :"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/dateTimeLongValue" />

<!--text views to show the current date and


time in formatted and human readable way-->
<TextView
android:id="@+id/format1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView" />

<TextView
android:id="@+id/format2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format1" />

<TextView
android:id="@+id/format3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format2" />

<TextView
android:id="@+id/format4"
android:layout_width="wrap_content"

Unit-3 Exploring User Interface Screen Elements Page 29


android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format3" />

<TextView
android:id="@+id/format5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format4" />

<TextView
android:id="@+id/format6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format5" />

<TextView
android:id="@+id/format7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="16dp"
android:textSize="18sp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/format6" />

</androidx.constraintlayout.widget.ConstraintLayout>

Step 3: Working with the MainActivity file

Understanding the way of formatting the date and time in Android using SimpleDateFormat

 Firstly, the instance of the Calendar is created and the desired format of the date and time to be
shown is passed to the SimpleDateFormat method. The String should include the following
characters and one may include the separators like -, / etc.
 The below table includes the characters to be used to generate the most used common pattern of
date and time.

Character to be used Output


dd Date in numeric value
E Day in String (short form. Ex: Mon)
EEEE Day in String (full form. Ex: Monday)
MM Month in numeric value
yyyy Year in numeric value
LLL Month in String (short form. Ex: Mar)
LLLL Month in String (full form. Ex: March)
HH Hour in numeric value (24hrs timing format)

Unit-3 Exploring User Interface Screen Elements Page 30


KK Hour in numeric value (12hrs timing format)
mm Minute in numeric value
ss Seconds in numeric value
aaa Displays AM or PM (according to 12hrs timing format)
z Displays the time zone of the region

ActivityMain.java

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

TextView dateTimeInLongTextView, format1, format2,


format3, format4, format5, format6, format7;

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

String dateTime;
Calendar calendar;
SimpleDateFormat simpleDateFormat;

// register all the text view with appropriate IDs


dateTimeInLongTextView = (TextView) findViewById(R.id.dateTimeLongValue);
format1 = (TextView) findViewById(R.id.format1);
format2 = (TextView) findViewById(R.id.format2);
format3 = (TextView) findViewById(R.id.format3);
format4 = (TextView) findViewById(R.id.format4);
format5 = (TextView) findViewById(R.id.format5);
format6 = (TextView) findViewById(R.id.format6);
format7 = (TextView) findViewById(R.id.format7);

// get the Long type value of the current system date


Long dateValueInLong = System.currentTimeMillis();
dateTimeInLongTextView.setText(dateValueInLong.toString());

// different format type to format the


// current date and time of the system
// format type 1
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format1.setText(dateTime);

// format type 2
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format2.setText(dateTime);

// format type 3
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss aaa z");

Unit-3 Exploring User Interface Screen Elements Page 31


dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format3.setText(dateTime);

// format type 4
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd.LLL.yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format4.setText(dateTime);

// format type 5
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("dd.LLLL.yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format5.setText(dateTime);

// format type 6
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("E.LLLL.yyyy HH:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format6.setText(dateTime);

// format type 7
calendar = Calendar.getInstance();
simpleDateFormat = new SimpleDateFormat("EEEE.LLLL.yyyy KK:mm:ss aaa z");
dateTime = simpleDateFormat.format(calendar.getTime()).toString();
format7.setText(dateTime);
}
}
Retrieving Data
SQLite is an open source SQL database that stores data to a text file on a device. Android comes in with
built in SQLite database implementation. SQLite supports all the relational database features. In order to
access this database, you don't need to establish any kind of connections for it like JDBC,ODBC e.t.c

Database – Package
The main package is android.database.sqlite that contains the classes to manage your own databases

Database – Creation
In order to create a database you just need to call this method openOrCreateDatabase with your database
name and mode as a parameter. It returns an instance of SQLite database which you have to receive in your
own object.
Its syntax is given below
SQLiteDatabase mydatabase = openOrCreateDatabase("your database name",MODE_PRIVATE,null);

Database - Insertion

We can create tables or insert data into tables using the execSQL method defined in SQLiteDatabase class.

Its syntax is given below

mydatabase.execSQL("CREATE TABLE IF NOT EXISTS Tbl_Login(Username VARCHAR,Password


VARCHAR);");

mydatabase.execSQL("INSERT INTO Tbl_Login VALUES('admin','admin');");

Database - Fetching

We can retrieve anything from the database using an object of the Cursor class. We will call a method of
this class called rawQuery and it will return a resultset with the cursor pointing to the table. We can move

Unit-3 Exploring User Interface Screen Elements Page 32


the cursor forward and retrieve the data.

Cursor resultSet = mydatbase.rawQuery("Select * from Tbl_Login",null); resultSet.moveToFirst();

String username = resultSet.getString(0);

String password = resultSet.getString(1);

Database - Helper class

For managing all the operations related to the database , a helper class has been given and is called
SQLiteOpenHelper. It automatically manages the creation and update of the database.

Its syntax is given below

public class DBHelper extends SQLiteOpenHelper {

public DBHelper(){

super(context,DATABASE_NAME,null,1);

public void onCreate(SQLiteDatabase db) {}

public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {}

Unit-3 Exploring User Interface Screen Elements Page 33


Unit-3 Exploring User Interface Screen Elements Page 34

You might also like