Android unit 3b
Android unit 3b
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:
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
android:columnWidth Defines the width of each column. Use “auto_fit” for default
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.
Step 4: Working with the XML Files
Next, go to the activity_main.xml file, which rep
<?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">
<WebView
android:id="@+id/web"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>
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
XML Attributes Description
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
public class CheckBox extends CompoundButton
It has two states – checked or unchecked.
Methods of CheckBox class
public boolean isChecked(): If CheckBox is in checked state then return true otherwise false.
public void setChecked(boolean status): It changes the state of the 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
XML attributes Description
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.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details
We are passing subject data to listview as shown below −
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"
/>