1.
Advanced User Interface
ListViews:
o A View that shows items in a vertically scrollable list. It's a subclass of
AdapterView which can display large datasets efficiently.
o Each item in the list is defined by a View that can be customized to fit your
app's needs (using ArrayAdapter, BaseAdapter etc.).
Android ListView is a view which groups several items and display them
in vertical scrollable list. The list items are automatically inserted to the
list using an Adapter that pulls content from a source such as an array or
database.
List View
An adapter actually bridges between UI components and the data source
that fill data into UI Component. Adapter holds the data and send the data
to adapter view, the view can takes the data from adapter view and shows
the data on different views like as spinner, list view, grid view etc.
The ListView and GridView are subclasses of AdapterView and they can
be populated by binding them to an Adapter, which retrieves data from an
external source and creates a View that represents each data entry.
Android provides several subclasses of Adapter that are useful for
retrieving different kinds of data and building views for an AdapterView (
i.e. ListView or GridView). The common adapters are ArrayAdapter,Base
Adapter, CursorAdapter, SimpleCursorAdapter,SpinnerAdapter and
WrapperListAdapter. We will see separate examples for both the
adapters.
ListView Attributes
Following are the important attributes specific to GridView −
Sr.No Attribute & Description
1 android:id
This is the ID which uniquely identifies the layout.
2 android:divider
This is drawable or color to draw between list items.
3 android:dividerHeight
This specifies height of the divider. This could be in px, dp, sp, in, or mm.
4 android:entries
Specifies the reference to an array resource that will populate the
ListView.
5 android:footerDividersEnabled
When set to false, the ListView will not draw the divider before each
footer view. The default value is true.
6 android:headerDividersEnabled
When set to false, the ListView will not draw the divider after each header
view. The default value is true.
WebViews:
o A WebView allows apps to display web content directly within the app.
o It is commonly used for loading web pages or running JavaScript within
an Android app.
ScrollView:
o A layout container that enables users to scroll through the content
vertically or horizontally.
o Useful when the content exceeds the screen size.
TabHosts:
o Used to create a tabbed navigation within an app. Each tab can contain a
fragment or an activity.
o It is being gradually replaced by TabLayout in newer Android design
patterns.
2. Android Menus
Option Menu:
o A primary collection of menu items for an activity, typically used for
global actions like settings or search.
o It is displayed when the user presses the menu button or the app bar
overflow button.
Context Menu:
o A floating menu that appears when the user performs a long-click on an
element.
o It is tied to a specific View and usually provides context-sensitive actions.
Popup Menu:
o Displays a list of items in a modal popup.
o It is attached to a view and provides a more compact way to show actions.
3. Fragments
What is a Fragment?
o A Fragment represents a portion of the user interface in an activity.
o They allow for more modular and flexible UI designs, especially on larger
screens like tablets.
Fragment Lifecycle:
Fragment Lifecycle in Android
In Android, the fragment is the part of the Activity that represents a portion of
the User Interface(UI) on the screen. It is the modular section of the Android
activity that is very helpful in creating UI designs that are flexible in nature and
auto-adjustable based on the device screen size. The UI flexibility on all devices
improves the user experience and adaptability of the application. that can exist
only inside an activity as its lifecycle is dependent on the lifecycle of the host
activity. For example, if the host activity is paused, then all the methods and
operations of the fragment related to that activity will stop functioning, the
fragment is also termed a sub-activity. Fragments in Android can be added,
removed, or replaced dynamically i.e., while the activity is running.
<fragment> tag is used to insert the fragment in an android activity layout. By
dividing the activity’s layout multiple fragments can be added in it.
Below is the pictorial representation of fragment interaction with the activity:
Understanding fragment lifecycles is crucial for building dynamic apps. For those
looking to master fragments using Kotlin, the Android Mastery with Kotlin:
Beginner to Advanced course covers everything from lifecycle management to
advanced implementations.
Types of Android Fragments
1. Single Fragment: Display only one single view on the device screen. This type of
fragment in android is mostly used for mobile phones.
1. List Fragment: This Fragment is used to display a list-view from which the user
can select the desired sub-activity. The menu drawer of apps like Gmail is the
best example of this kind of android fragment.
1. Fragment Transaction: This kind of fragments in android supports the
transition from one fragment in android to another at run time. Users can switch
between multiple fragments like switching tabs.
ANdroid Fragment Lifecycle
Each fragment has it’s own lifecycle but due to the connection with the Activity it
belongs to, the android fragment lifecycle is influenced by the activity’s lifecycle.
Methods of the Android Fragment
Methods Description
The very first method to be called when the
fragment has been associated with the activity. This
method executes only once during the lifetime of a
fragment.
onAttach()
When we attach fragment(child) to Main(parent)
activity then it call first and then not call this method
any time(like you run an app and close and reopen)
simple means that this method call only one time.
This method initializes the fragment by adding all
onCreate()
the required attributes and components.
onCreateView() System calls this method to create the user interface
of the fragment. The root of the fragment’s layout is
returned as the View component by this method to
draw the UI.
You should inflate your layout in onCreateView but
shouldn’t initialize other views using findViewById
in onCreateView.
It indicates that the activity has been created in
onViewCreated() which the fragment exists. View hierarchy of the
fragment also instantiated before this function call.
The system invokes this method to make the
onStart()
fragment visible on the user’s device.
This method is called to make the visible fragment
onResume()
interactive.
It indicates that the user is leaving the fragment.
onPause() System call this method to commit the changes made
to the fragment.
Method to terminate the functioning and visibility of
onStop()
fragment from the user’s screen.
System calls this method to clean up all kinds of
resources as well as view hierarchy associated with
onDestroyView()
the fragment. It will call when you can attach new
fragment and destroy existing fragment Resoruce
It is called to perform the final clean up of fragment’s
onDestroy()
state and its lifecycle.
The system executes this method to disassociate the
fragment from its host activity.
onDetach()
It will call when your fragment Destroy(app crash or
attach new fragment with existing fragment)
Android Fragment When to call Method
Consider Fragment-1 is A and Fragment-2 is B and A is attached to the Main
Activity
1. If you can replace B with A.
A’s call back:
onDestroyView()
onDestroy()
onDetach()
B’s call back:
onAttach()
onCreate()
onCreateView()
onViewCreated()
2. If you can replace B with A without Losing resources.
A’s call back:
onDestroy()
onDetach()
B’s call back:
onAttach()
onCreate()
onCreateView()
onViewCreated()
Example of Android Fragment
Fragments in android are always embedded in Activities i.e., they are added to
the layout of activity in which they reside. Multiple fragments can be added to
one activity. This task can be carried out in 2 ways:
1. Statically: Explicitly mention the fragment in the XML file of the activity. This
type of fragment can not be replaced during the run time.
1. Dynamically: FragmentManager is used to embed fragments with activities that
enable the addition, deletion, or replacement of fragments at run time.
Almost all android app uses dynamic addition of fragments as it improves the
user experience. Below is the step-by-step implementation of adding 2 fragments
in one activity. A default fragment will be visible when the activity appears on
the screen and the user can switch between the 2 fragments at the run time.
Note: Following steps are performed on Android Studio version 4.0
Step 1: Create a new project
1. Click on File, then New => New Project.
1. Choose Empty activity
1. Select language as Java
1. Select the minimum SDK as per your need.
Step 2: Modify strings.xml file
All the strings which are used in the activity are listed in this file
XML
<resources>
<string name="app_name">GfG | Fragment in Android</string>
<string name="heading">Two Fragments in One Activity</string>
<string name="fragment1_button">Display First Fragment</string>
<string name="fragment2_button">Display Second Fragment</string>
<string name="fragment1_text1">Displaying contents of the First
Fragment</string>
<string name="fragment2_text1">Displaying contents of the Second
Fragment</string>
</resources>
Step 3: Working with the activity_main.xml file
Open the activity_main.xml file and add 2 buttons to it which will be used to
switch between the 2 fragments. Further, add the fragment element in the
activity layout. It is the area in which the fragments in android will be displayed.
XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#168BC34A"
android:orientation="vertical"
tools:context=".MainActivity">
<!-- Heading of the activity -->
<TextView
android:id="@+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginBottom="20dp"
android:fontFamily="@font/roboto"
android:text="@string/heading"
android:textAlignment="center"
android:textColor="@android:color/holo_green_light"
android:textSize="24sp"
android:textStyle="bold" />
<!-- Button to display first fragment -->
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginEnd="20dp"
android:background="#4CAF50"
android:fontFamily="@font/roboto"
android:onClick="selectFragment"
android:text="@string/fragment1_button"
android:textColor="@android:color/background_light"
android:textSize="18sp"
android:textStyle="bold" />
<!-- Button to display second fragment -->
<Button
android:id="@+id/button2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="20dp"
android:layout_marginBottom="20dp"
android:background="#4CAF50"
android:fontFamily="@font/roboto"
android:onClick="selectFragment"
android:text="@string/fragment2_button"
android:textColor="@android:color/background_light"
android:textSize="18sp"
android:textStyle="bold" />
<!-- Adding Fragment element in the activity -->
<fragment
android:id="@+id/fragment_section"
android:name="com.example.fragments_backup.FragmentOne"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginStart="10dp"
android:layout_marginEnd="10dp"
android:layout_marginBottom="10dp"
tools:layout="@layout/fragment_one" />
</LinearLayout>
The android:name tag under the <fragment> element is containing the file name
of default fragment which is to be displayed when activity opens.
Step 4: Creating the two fragment class
These files contain only the onCreateView() method to inflate the UI of the
fragment and returns the root of the fragment layout. If the fragment does not
have any UI, it will return null.
1. First Fragment class:
Java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentOne extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflating the layout of the fragment
// and returning the view component
return inflater.inflate(R.layout.fragment_one, container, false);
2. Second Fragment Class:
Java
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class FragmentTwo extends Fragment{
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// inflating the layout of the fragment
// and returning the view component
return inflater.inflate(R.layout.fragment_two, container, false);
Step 5: Creating Layouts for both the fragments
Create two Layout Resource Files for both the fragments. Fragment displays a
text on the screen and have a background color to differentiate their area in the
Activity layout. Below is the code to implement this layout.
1. fragment_one.xml file:
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:background="#5C52CC57"
android:orientation="vertical">
<!-- Text to be displayed inside the Fragment -->
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:gravity="center"
android:text="@string/fragment1_text1"
android:textAlignment="center"
android:textColor="@android:color/background_light"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
2. fragment_two.xml file:
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:background="#5C3473A6"
android:orientation="vertical">
<!-- Text to be displayed inside the Fragment -->
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fontFamily="@font/roboto"
android:gravity="center"
android:text="@string/fragment2_text1"
android:textAlignment="center"
android:textColor="@android:color/background_light"
android:textSize="24sp"
android:textStyle="bold" />
</LinearLayout>
Step 6: Working with the MainActivity.java file
Now, the functionality of the button to perform operations on clicking will be
defined in the MainActivity class. Moreover, the code for the replacement of
fragments during run time is also mentioned in this file. Below is the code to
implement this step.
Java
import android.os.Bundle;
import android.view.View;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// method for displaying the appropriate
// fragment according to the clicked button
public void selectFragment(View view) {
// creating object for Fragment
Fragment fr;
// displaying first fragment
// if button1 is clicked
if(view == findViewById(R.id.button1)) {
fr = new FragmentOne();
// displaying second fragment
// if button2 is clicked
else {
fr = new FragmentTwo();
FragmentManager fm = getFragmentManager();
// fragment transaction to add or replace
// fragments while activity is running
FragmentTransaction fragmentTransaction = fm.beginTransaction();
fragmentTransaction.replace(R.id.fragment_section, fr);
// making a commit after the transaction
// to assure that the change is effective
fragmentTransaction.commit();
o Key lifecycle methods include:
onAttach(): Called when a fragment is first attached to its activity.
onCreateView(): Inflate the fragment's UI.
onActivityCreated(): When the parent activity's onCreate() method
has finished execution.
onStart(), onResume(): These methods deal with the fragment
becoming visible to the user.
onPause(), onStop(): Manage when the fragment is no longer
visible or is being replaced.
onDestroyView(), onDetach(): Cleanup before the fragment is fully
removed.
Dynamic Fragments:
o These are fragments that are created or removed dynamically (at
runtime), usually via FragmentTransaction.
o This allows more control over the UI layout, adapting to changes like
screen rotation or device configurations.
4. Notifications
Standard Notifications:
o Notifications are used to inform users of important events while not
interrupting their current activities.
o Notifications are displayed in the status bar and can be interacted with by
tapping, leading the user to a specific action or screen.
Custom Notifications:
o Custom notifications go beyond the standard templates and allow you to
design your own notification layout using custom views.
o Useful for more personalized or branded notifications with complex
layouts, colors, and content.