Android unit 3
Android unit 3
User
Interface (UI) defines the way humans interact with the information systems. In Layman’s terms, User
Interface (UI) is a series of pages, screens, buttons, forms, and other visual elements that are used to
interact with the device. Every app and every website has a user interface. User Interface (UI) Design
is the creation of graphics, illustrations, and the use of photographic artwork and typography to
enhance the display and layout of a digital product within its various device views.
Types of UI Design
Some common types of User Interface(UI) are:
GUI (Graphical User Interface): Visual user interface output (keyboard and monitor) with a
tactile user interface input.
Menu Driven Interface: An UI that uses a menu of options to navigate a program or website
is known as a menu-driven UI. For instance, ATMs have user interfaces that are menu-driven
and simple to use.
Form Based Interface: Form-based user interfaces provide a small number of options for
users to choose from when entering data into a program or application. For instance, a
device’s settings menu is form-based.
Touch user interface: Haptic or tactile user interface. Haptic input is used by
most smartphones, tablets, and other devices with touch screens.
Voice user interface: Auditory commands are used to communicate between humans and
machines. GPS, talk-to-text gadgets, and virtual assistants are a few examples.
Advantages of UI Design
No need to learn complex commands/languages for working with UI.
Easiness for non-technical people. A beginner can navigate through a site with ease if its
simple and well informative.
Usage of blocks and typography makes user experience better.
Easy setup and ready to start working are awesome. Hiding the complexity of actions from
the user and display only the required information is key to good interface.
Disadvantages of UI Design
When not properly built, it can be very difficult to work with.
Takes time to built a Perfect UI Design.
May lack customization options, preventing users from adapting the interface to their
preferences or workflow.
Designing User Interfaces with Layouts
Layouts in Android define the user interface and hold UI controls or widgets that appear on the
screen of an application. Every Android application consists of View and ViewGroup elements. Since
an application contains multiple activities—each representing a separate screen—every activity has
multiple UI components.
View and ViewGroup
A View is used to create interactive UI components such
as TextView, ImageView, EditText, RadioButton, etc., and is responsible for event handling and
drawing. They are Called Widgets. A ViewGroup act as a base class for layouts and layouts
parameters that hold other Views or ViewGroups and to define the layout properties. They are
generally Called layouts.
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="16dp"
android:hint="Input"
android:inputType="text"/>
<Button
android:id="@+id/showInput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="show"
android:backgroundTint="@color/colorPrimary"
android:textColor="@android:color/white"/>
</LinearLayout>
Design UI:
Methods Description
strings.xml:
<resources>
<string name="app_name">GFG App</string>
<string name="blink">BLINK</string>
<string name="clockwise">ROTATE</string>
<string name="fade">FADE</string>
</resources>
Step 3: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml. Create ImageView in
the activity_main.xml along with buttons that will add animation to the view.
activity_main.xml:
<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"
android:gravity="center_horizontal"
tools:context=".MainActivity">
<ImageView
android:id="@+id/imageview"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginTop="40dp"
android:contentDescription="@string/app_name"
android:src="@drawable/gfg_logo" />
<LinearLayout
android:id="@+id/linear1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:orientation="horizontal"
android:weightSum="3">
</LinearLayout>
Layouts
Layout Managers (or simply layouts) are said to be extensions of the ViewGroup class. They are used
to set the position of child Views within the UI we are building. There is a number of layout classes in
the Android SDK. They can be used, modified or can create your own to make the UI for your Views,
Fragments and Activities.
Types of Layouts
1. ConstraintLayout
Constraint Layout is a flexible layout that allows views to be positioned using constraints instead of
nesting layouts. It helps in reducing the view hierarchy and improves performance by a lot. It is
the most popular and recommended layout for designing complex interfaces in modern Android
applications.
2. LinearLayout
A LinearLayout aligns each of the view in a single direction either a vertical or a horizontal manner. A
layout in vertical manner has a single column of views, whereas in a layout in horizontal manner, has
a single row of views. It supports a weight attribute for each view that can control the relative size of
each view within the available space.
3. FrameLayout
Frame Layout is a simple layout mainly used to hold a single child view, though multiple views can be
stacked on top of each other. It is commonly used for overlays, fragments, and simple UI components
like image views.
4. RelativeLayout
Relative layout allows views to be relative to one another or to the parent layout. This makes
positioning flexible as we can position views to the left, right, top, or bottom of other views. However
after Constraint Layout was introduced, the use of Relative Layout has ceased since Constraint Layout
is much better as handling large UIs.
5. TableLayout
TableLayout arranges views in a grid-like format using rows and columns, similar to an HTML table. It
is useful for displaying structured data, such as forms or spreadsheets. Each row consists of
multiple TableRow elements, and views within rows can be assigned specific column spans
6. GridLayout
Introduced in Android 4.0 (API level 14), the GridLayout is an advanced and more flexible alternative
to TableLayout. It divides the screen into a matrix of rows and columns, allowing precise placement
of elements without needing of nested layouts. It is efficient for creating grid-based UIs like image
galleries or dashboards.
RecyclerView
RecyclerView is an advanced and flexible version of ListView and GridView. It is a container used
for displaying large amount of data sets that can be scrolled very efficiently by maintaining a limited
number of views.
This new widget is a big step for displaying data in Material Design because the ListView and
GridView are one of the most commonly used UI widget. In RecyclerView android provides a lots of
new features which are not present in existing ListView or GridView. In Android, RecyclerView
provides an ability to implement the horizontal, vertical and Expandable List. It is mainly used when
we have data collections whose elements can change at run time based on user action or any
network events. For using this widget we have to specify the Adapter and Layout Manager.
Basic RecyclerView XML code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="abhiandroid.com.recyclerviewexample.MainActivity">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Components of RecyclerView In Android
1. Layout Managers:
In Android a RecyclerView needs to have a Layout Manager and an Adapter to be instantiated.
Layout Manager is a very new concept introduced in RecyclerView for defining the type of Layout
which RecyclerView should use. It Contains the references for all the views that are filled by the data
of the entry. We can create a Custom Layout Manager by extending RecyclerView.LayoutManager
Class
2.ViewHolder: ViewHolder is used to store the reference of the View’s for one entry in the
RecyclerView. A ViewHolder is a static inner class in our Adapter which holds references to the
relevant view’s. By using these references our code can avoid time consuming findViewById()
method to update the widgets with new data
3. RecyclerView.Adapter:
RecyclerView includes a new kind of Adapter. It’s a similar approach to the ones we already used but
with some peculiarities such as a required ViewHolder for handling Views. We will have to override
two main methods first one to inflate the view and its viewholder and another one to bind the data
to the view. The main good thing in this is that the first method is called only when we really need to
create a new view.
4. ItemAnimator: RecyclerView.ItemAnimator will animate ViewGroup modification such as delete,
select, add that notify the Adapter. DefaultItemAnimator can be used for providing default Animation
and it works quite well.
ListView
A ListView in Android is a type of AdapterView that displays a vertically scrollable list of items, with
each item positioned one below the other. Using an adapter, items are inserted into the list from an
array or database efficiently. For displaying the items in the list method setAdaptor() is used.
The setAdaptor() method binds the adapter with the ListView.
ListView in Android is a ViewGroup that is used to display the list of items in multiple rows and
contains an adapter that automatically inserts the items into the list dynamically. The main purpose
of the adapter is to retrieve data from an array or database and dynamically insert each item into the
list for the desired result. Adapters can fetch data from various sources including resources like
the strings.xml file.
Some Important XML Attributes of ListView
Attribute Description
GridView
A GridView is a type of AdapterView that displays items in a two-dimensional scrolling grid. Items are
inserted into this grid layout from a database or from an array. The adapter is used for displaying this
data, setAdapter() method is used to join the adapter with GridView. The main function of the
adapter in GridView is to fetch data from a database or array and insert each piece of data in an
appropriate item that will be displayed in GridView.
Some Important XML attributes of GridView
Attribute Description
WebView
WebView is a view that displays web pages as a part of the application layout. It is used to embed a
complete website into an app.
Step 1: Create a New Project in Android Studio
Step 2: Adding Permissions to the AndroidManifest.xml File
In AndroidManifest.xml, one needs to include the below permission, in order to access the Internet.
<uses-permission android:name="android.permission.INTERNET"/>
Step 3: Working with the MainActivity File
Go to the MainActivity File and refer to the following code. Below is the code for the MainActivity
File.
Buttons:
In Android applications, a Button is a user interface that is used to perform some action when
clicked or tapped.
XML Attributes of Button Widget
android:textStyle Used to the display style of the text like Bold, Italic, etc.
Used to specify the gravity of the view like center, top, bottom,
android:gravity
etc
CheckBox
CheckBox belongs to android.widget.CheckBox class. Android CheckBox class is the subclass of
CompoundButton class. It is generally used in a place where user can select one or more than
choices from a given list of choices.
Syntax of CheckBox
Example of CheckBox
activity_main.xml:
<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"
android:background="#ffffff"
android:orientation="vertical">
<CheckBox
android:id="@+id/checkBox"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Painting"
android:layout_marginTop="16dp"
android:textSize="16sp" />
<CheckBox
android:id="@+id/checkBox2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Reading"
android:layout_marginTop="16dp"
android:textSize="16sp" />
</LinearLayout>
Radio Buttons
Android radio button is a widget that can have more than one option to choose from. The user can
choose only one option at a time. Each option here refers to a radio button and all the options for the
topic are together referred to as Radio Group. Hence, Radio Buttons are used inside a RadioGroup.
Step 1: First create a new Android Application. This will create an XML file “activity_main.xml”
<RadioGroup
android:id="@+id/groupradio"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:orientation="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/text_view1">
<RadioButton
android:id="@+id/radia_id1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="DBMS"
android:textSize="20sp" />
<RadioButton
android:id="@+id/radia_id2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="C/C++ Programming"
android:textSize="20sp" />
</RadioGroup>
Step 2: Add the syntax to java file
RadioGroup radioGroup = findViewById(R.id.groupradio);
Unset all the Radio Buttons initially as the default value. This is done by the following command:
radioGroup.clearCheck();
Add the Listener on the RadioGroup. This will help to know whenever the user clicks on any Radio
Button, and the further operation will be performed. The listener can be added as follows:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){}
Define the operations to be done when a radio button is clicked.
submit.setOnClickListener(new View.OnClickListener() {}
clear.setOnClickListener(new View.OnClickListener() {}
ToggleButton
A ToggleButton displays checked/unchecked states as a button. It is basically an on/off button with a
light indicator.
ToggleButton Attributes
Sr.No. Attribute & Description
android:disabledAlpha
1
This is the alpha to apply to the indicator when disabled.
android:textOff
2
This is the text for the button when it is not checked.
android:textOn
3
This is the text for the button when it is checked.
Inherited from android.widget.TextView Class
Example:
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="On"
android:id="@+id/toggleButton"
android:checked="true"
android:layout_below="@+id/imageButton"
android:layout_toEndOf="@+id/button2/>
Spinner
Spinner is a view similar to the dropdown list which is used to select one option from the list of
options. It provides an easy way to select one item from the list of items and it shows a dropdown list
of all values when we click on it. The default value of the android spinner will be the currently
selected
Attributes for Spinner Widget
android:gravity Used to specify the gravity of the view like center, top, bottom, etc
Example:
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingHorizontal="16dp"
android:paddingVertical="8dp"/>
Input Events: 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 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 Listener Methods:
1. onClick(): This method is called when the user touches the item or focuses upon the item with the
navigation-keys or trackball and presses the suitable “enter” key or presses down on the trackball.
2.onLongClick():This is called when the user either touches and holds the item, or focuses upon the
item with the navigation-keys or trackball and presses and holds the suitable “enter” key or presses
and holds down on the trackball (for one second).
3. onFocusChange(): This is called when the user navigates onto or away from the item, using the
navigation-keys or trackball.
4. onKey(): This is called when the user is focused on the item and presses or releases a hardware
key on the device.
5. onTouch(): This is called when the user acts qualified as a touch event, including a press, a
release, or any movement gesture on the screen (within the bounds of the item).
Event Handlers:
Method Description
onTrackballEvent(
This method is called when a trackball motion event occurs.
)
onTouchEvent() This method is called when a touch screen motion event occurs.
onFocusChanged() This method is called when the view gains or loses focus.
Android Menus
Menus are an essential part of Android UI design, offering users a smooth and consistent navigation
experience. With the help of menu, users can experience a smooth and consistent experience
throughout the application. To define menus efficiently and maintain clean code, Android
recommends using XML menu resources instead of programmatically creating menus in your
activities or fragments. This approach ensures better organization and easier maintenance.
menu_example.xml:
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/mail"
android:icon="@drawable/mail"
android:title="Mail"/>
<item
android:id="@+id/upload"
android:icon="@drawable/upload"
android:title="Upload"/>
<item
android:id="@+id/share"
android:icon="@drawable/share"
android:title="Share"/>
</menu>
Different type of tags:
<menu>: It is the root element that helps in defining Menu in XML file and it also holds
multiple elements.
<item>: It is used to create a single item in the menu. It also contains nested <menu>
element in order to create a submenu.
<group>: It is optional and invisible for <item> elements to categorize the menu items so
they can share properties like active state, and visibility.
Different Types of Menus
Android Options Menu: is a primary collection of menu items in an android application and
is useful for actions that have a global impact on the searching application.
Android Context Menu: is a floating menu that only appears when the user clicks for a
long time on an element and is useful for elements that affect the selected content or
context frame.
Android Popup Menu: displays a list of items in a vertical list which presents the view that
invoked the menu and is useful to provide an overflow of actions related to specific
content.
Toast in Android: A Toast is a feedback message. It takes a very little space for displaying while the
overall activity is interactive and visible to the user. It disappears after a few seconds
automatically.There are only 2 constants of Toast class which are given below.
public static final int LENGTH_LONG: It displays view for the long duration of time.
public static final int LENGTH_SHORT: It displays view for the short duration of time.
Methods of Toast class:
public static Toast makeText(Context context, CharSequence text, int duration): makes the toast
containing text and duration.
public void show(): displays toast.
public void setMargin (float horizontalMargin, float verticalMargin): changes the horizontal and
vertical margin difference.
Example: Toast t=Toast.makeText(getApplicationContext(),"Hello Javatpoint",Toast.LENGTH_SHORT);
t.setMargin(50,50);
t.show();
Dialogs: A dialog is a small window that prompts the user to make a decision or enter additional
information. A dialog doesn't fill the screen and is normally used for modal events that require users
to take an action before they can proceed.
Types of Dialog:
In android, you can create following types of Dialogs:
1.Alert Dialog
2.DatePicker Dialog
3.TimePicker Dialog
4.Custom Dialog
1.Alert Dialog:
Android AlertDialog can be used to display the dialog message with OK and Cancel buttons. It can be
used to interrupt and ask the user about his/her choice to continue or discontinue. This Dialog
maximum 3 buttons allowed.
Syntax: AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
2.DatePicker Dialog:
Android DatePickerDialog puts a DatePicker on a Dialog. It allows user to select Date(day,month and
year) in our application.
3.TimePicker Dialog:
Android TimePicker is a component that permits users to select a time including hour and
minute.Android Time Picker allows you to select the time of day in either 24 hour or AM/PM mode.
The time consists of hours, minutes and clock format or spinner format. Android provides this
functionality through TimePicker class.
TimePicker has two modes with different interface:
1.Clock
2.Spinner
Clock Mode:
Clock mode is the default mode of the TimePicker, in which the user can visually select the time just
like he/ she is adjusting the time on a clock.
Syntax: TimePicker timePicker = (TimePicker) this.findViewById(R.id.timePicker);
timePicker.setIs24HourView(true);
Spinner Mode:
In Spinner mode, a TimePicker consists of 2 or 3 Spinners. These Spinners respectively allows the
user to select the hour, the minute, and either AM or PM.
Syntax: TimePicker timePicker = (TimePicker) this.findViewById(R.id.timePicker);
timePicker.setIs24HourView(true);
4.Custom Dialog
You can create your own custom dialog with custom characteristics.
Android ListView
A ListView in Android is a type of AdapterView that displays a vertically scrollable list of items, with
each item positioned one below the other. Using an adapter, items are inserted into the list from an
array or database efficiently. For displaying the items in the list method setAdaptor() is used.
The setAdaptor() method binds the adapter with the ListView. ListView in Android is a ViewGroup
that is used to display the list of items in multiple rows and contains an adapter that automatically
inserts the items into the list dynamically. The main purpose of the adapter is to retrieve data from
an array or database and dynamically insert each item into the list for the desired result. Adapters
can fetch data from various sources including resources like the strings.xml file.
String tutorials[] = { "Algorithms",
"Data Structures",
"Languages",
"Interview Corner",
"GATE",
"ISRO CS",
"UGC NET CS",
"CS Subjects",
"Web Technologies" };
custom listview:
Custom listview works based on customAdapter. In this custom adapter we can pass custom object.
We are passing subject data to listview as shown below −
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details
to create a new project. In the xml file, we have declared a listview and added divider as shown
below.
<ListView
android:id = "@+id/list"
android:layout_width = "wrap_content"
android:layout_height = "match_parent"
android:divider = "#000"
android:dividerHeight = "1dp"
android:footerDividersEnabled = "false"
android:headerDividersEnabled = "false"
/>