Unit 5 Advanced UI Components
Unit 5 Advanced UI Components
Advanced UI Components
Methods of DatePicker
Let’s discuss some common methods of a datepicker which are used to configure a DatePicker in our application.
1. setSpinnersShown(boolean shown):
This method is used to set whether the spinner of the date picker in shown or not. In this method you have to set a Boolean
value either true or false. True indicates spinner is shown, false value indicates spinner is not shown. Default value for this
function is true.
Below we show the use of setSpinnerShown() function by setting false value.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker
2. getDayOfMonth():
This method is used to get the selected day of the month from a date picker. This method returns an integer
value.
Below we get the selected day of the month from a date picker.
/*Add in Oncreate() funtion after setContentView()*/
DatePicker simpleDatePicker = (DatePicker) findViewById(R.id.simpleDatePicker); // initiate a date picker
int day = simpleDatePicker.getDayOfMonth(); // get the selected day of the month
3. getMonth():
This method is used to get the selected month from a date picker. This method returns an integer value.
Below we get the selected month from a date picker.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker
int month = simpleDatePicker.getMonth(); // get the selected month
4. getYear():
This method is used to get the selected year from a date picker. This method returns an integer value.
Below code is used to get the selected year from a date picker.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker
int year = simpleDatePicker.getYear(); // get the selected year
5. getFirstDayOfWeek():
This method is used to get the first day of the week. This method returns an integer value.
Below code is used to get the first day of the week.
DatePicker simpleDatePicker = (DatePicker)findViewById(R.id.simpleDatePicker); // initiate a date picker
Time
In Android, TimePicker is a widget used for selecting the time of the day in either AM/PM mode or 24 hours mode. The
displayed time consist of hours, minutes and clock format. If we need to show this view as a Dialog then we have to use a
TimePickerDialog class.
TimePicker code:
<TimePicker
android:id="@+id/simpleTimePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:timePickerMode="spinner"/>
Methods of TimePicker:
Let’s discuss some common methods of a time picker, which are used to configure a time picker in our
application.
1. setCurrentHour(Integer currentHour):
This method is used to set the current hours in a time picker.
setHour(Integer hour): setCurrentHour() method was deprecated in API level 23. From api level 23 we have
to use setHour(Integer hour). In this method there is only one parameter of integer type which is used to set
the value for hours.
Below we set the 5 value for the current hours.
TimePicker simpleTimePicker=(TimePicker)findViewById(R.id.simpleTimePicker); // initiate a time picker
// set the value for current hours
simpleTimePicker.setCurrentHour(5); // before api level 23
simpleTimePicker.setHour(5); // from api level 23
2. setCurrentMinute(Integer currentMinute):
This method is used to set the current minutes in a time picker.
setMinute(Integer minute): setCurrentMinute() method was deprecated in API level 23. From api level 23
we have to use setMinute(Integer minute). In this method there is only one parameter of integer type
which set the value for minutes.
Below we set the 35 value for the current minutes.
TimePicker simpleTimePicker=(TimePicker)findViewById(R.id.simpleTimePicker); // initiate a time picker
// set the value for current hours
simpleTimePicker.setCurrentMinute(35); // before api level 23
simpleTimePicker.setMinute(35); // from api level 23
3. getCurrentHour():
This method is used to get the current hours from a time picker.
getCurrentHour(): getCurrentHour() method was deprecated in API level 23. From api level 23 you have to
use getHour(). This method returns an integer value.
TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker); // initiate a time
pickerint hours =simpleTimePicker.getCurrentHour(); // before api level 23
int hours =simpleTimePicker.getHour(); // after api level 23
4. getCurrentMinute():
This method is used to get the current minutes from a time picker.
getMinute(): getCurrentMinute() method was deprecated in API level 23. From api level 23 we have to
use getMinute(). This method returns an integer value.
Below we get the value of minutes from a time picker.
TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker); // initiate a time picker
int minutes = simpleTimePicker.getCurrentMinute(); // before api level 23
int minutes = simpleTimePicker.getMinute(); // after api level 23
5. setIs24HourView(Boolean is24HourView):
This method is used to set the mode of the Time picker either 24 hour mode or AM/PM mode. In this method
we set a Boolean value either true or false. True value indicate 24 hour mode and false value indicate AM/PM
mode.
Below we set the current mode of the time picker.
TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker); // initiate a time picker
simpleTimePicker.setIs24HourView(true); // set 24 hours mode for the time picker
6. is24HourView():
This method is used to check the current mode of the time picker. This method returns true if its 24 hour mode
or false if AM/PM mode is set.
Below we get the current mode of the time picker:
TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker); // initiate a time picker
Boolean mode=simpleTimePicker.is24HourView(); // check the current mode of the time picker
7. setOnTimeChangedListener(TimePicker.OnTimeChangedListener onTimeChangedListener):
This method is used to set the callback that indicates the time has been adjusted by the user.
onTimeChanged(TimePicker view, int hourOfDay, int minute) is an override function of this listener in which
we have three parameters first is for TimePicker, second for getting hour of the day and last is for getting the
minutes after changing the time of the time picker.
Below we show the use of on time changed listener of a time picker.
TimePicker simpleTimePicker = (TimePicker)findViewById(R.id.simpleTimePicker); // initiate a time picker
simpleTimePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
@Override
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
}
});
List View
List of scrollable items can be displayed in Android using ListView. It helps you to displaying the data in the
form of a scrollable list. Users can then select any list item by clicking on it. ListView is default scrollable so
we do not need to use scroll View or anything else with ListView.
ListView is widely used in android applications. A very common example of ListView is your phone contact
book, where you have a list of your contacts displayed in a ListView and if you click on it then user information
is displayed.
ListView in Android Studio: Listview is present inside Containers. From there you can drag and drop on
virtual mobile screen to create it. Alternatively you can also XML code to create it.
Grid View
In android GridView is a view group that display items in two dimensional scrolling grid (rows and columns), the grid items are
not necessarily predetermined but they are automatically inserted to the layout using a ListAdapter. Users can then select any
grid item by clicking on it. GridView is default scrollable so we don’t need to use ScrollView or anything else with GridView.
GridView is widely used in android applications. An example of GridView is your default Gallery, where you have number of
images displayed using grid.
Adapter Is Used To Fill Data In Gridview: To fill the data in a GridView we simply use adapter and grid items are
automatically inserted to a GridView using an Adapter which pulls the content from a source such as an arraylist, array or
database.
GridView in Android Studio: Gridview is present inside Containers. From there you can drag and drop on virtual mobile
screen to create it. Alternatively you can also XML code to create it.
RecyclerView
In Android, 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. RecyclerView was introduced in Material Design in API level 21 (Android 5.0 i.e Lollipop).
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.
Important Note:
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>
Gradle Dependency to use RecyclerView:
The RecyclerView widget is a part of separate library valid for API 7 level or higher. Add the following
dependency in your Gradle build file to use recyclerview.
Need of RecyclerView In Android
RecyclerView uses a ViewHolder for storing the reference of the view for one entry in the RecyclerView. When
we use ListView or GridView for displaying custom items then we create a custom xml file and then use it
inside our Adapter. For this we create a CustomAdapter class and then extends our Base or any other Adapter in
it. In getView() method of our Adapter we inflate the item layout xml file and then give the reference of every
view by using the unique id’s we provide in our xml file . Once finished we pass that view to the ListView,
ready to be drawn, but the truth is that ListView and GridView do only half the job of achieving true memory
efficiency.
Components of RecyclerView In Android
Below we define the mainly used components of a RecyclerView.
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 but RecyclerView Provides three types of
in-built Layout Managers.
Linear Layout Manager – It is used for displaying the data items in a horizontal or vertical scrolling List
GridLayoutManager – It is used to show the items in grid format
StaggeredGridLayoutManager – It is used to show the items in staggered Grid.
Below we explain each type in details:
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.
Adapter: To fill the data in a ListView we simply use adapters. List items are automatically inserted to a
list using an Adapter that pulls the content from a source such as an arraylist, array or database.
An adapter is a bridge between UI component and data source that helps us to fill data in UI component. It
holds the data and send the data to adapter view then view can takes the data from the adapter view and shows
the data on different views like as list view, grid view, spinner etc.
ListView is a subclass of AdapterView and it can be populated by binding to an Adapter, which retrieves the
data from an external source and creates a View that represents each data entry.
In android commonly used adapters are:
1. Array Adapter
2. Base Adapter
Now we explain these two adapter in detail:
1.Array Adapter:
Whenever you have a list of single items which is backed by an array, you can use ArrayAdapter. For instance,
list of phone contacts, countries or names.
Important Note: By default, ArrayAdapter expects a Layout with a single TextView, If you want to use more
complex views means more customization in list items, please avoid ArrayAdapter and use custom adapters.
Below is Array Adapter code:
ArrayAdapter adapter = new ArrayAdapter<String>(this,R.layout.ListView,R.id.textView,StringArray);
Example of Array Adapter:
In this example, we display a list of countries by using simple array adapter. Below is the final output we will
create:
2.Base Adapter:
BaseAdapter is a common base class of a general implementation of an Adapter that can be used in ListView.
Whenever you need a customized list you create your own adapter and extend base adapter in that. Base
Adapter can be extended to create a custom Adapter for displaying a custom list item. ArrayAdapter is also an
implementation of BaseAdapter.
Example of list view using Custom adapter(Base adapter):
In this example we display a list of countries with flags. For this, we have to use custom adapter as shown in
example:
ViewHolder
A ViewHolder describes an item view and metadata about its place within the RecyclerView. RecyclerView. Adapter
implementations should subclass ViewHolder and add fields for caching potentially expensive View.
The ViewHolder design pattern enables you to access each list item view without the need for the look up, saving valuable
processor cycles. Specifically, it avoids frequent call of findViewById() during ListView scrolling, and that will make it
smooth.
Without the ViewHolder Design Pattern
Okay, let’s dig it out and see how it works without the ViewHolder pattern.
Let’s take a look at our previous getView() method in ArrayAdapterItem.java
1. The first time it was loaded, convertView is null. We’ll have to inflate our list item layout and find the TextView
via findViewById().
2. The second time it was loaded, convertView is not null, good! We don’t have to inflate it again. But we’ll
use findViewById() again.
3. The following times it was loaded, convertView is definitely not null. But findViewById() is constantly called, it will
work but, it slows down the performance especially if you have lots of items and Views in your ListView.
With the ViewHolder Design Pattern
Now let’s see how it works with the ViewHolder pattern.
1. The first time it was loaded, convertView is null. We’ll have to inflate our list item layout, instantiate the ViewHolder,
find the TextView via findViewById() and assign it to the ViewHolder, and set the ViewHolder as tag of convertView.
2. The second time it was loaded, convertView is not null, good! We don’t have to inflate it again. And here’s the sweet
thing, we won’t have to call findViewById() since we can now access the TextView via its ViewHolder.
3. The following time it was loaded, convertView is definitely not null. The findViewById() is never called again, and
that makes our smooth ListView scrolling.
Dialogs
A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog
does not fill the screen and is normally used for events that require users to take an action before they can
proceed.
In android, you can create following types of Dialogs:
Alert Dialog
DatePicker Dialog
TimePicker Dialog
Custom Dialog
Alert Dialog
This Dialog is used to show a title, buttons(maximum 3 buttons allowed), a list of selectable items, or a custom
layout.
DatePicker Dialog
This dialog provides us with a pre-defined UI that allows the user to select a date.
TimePicker Dialog
This dialog provides us with a pre-defined UI that allows the user to select suitable time.
Custom Dialog
You can create your own custom dialog with custom characteristics.
Alert Dialog shows the Alert message and gives the answer in the form of yes or no. Alert Dialog displays the
message to warn you and then according to your response the next step is processed.
Android Alert Dialog is built with the use of three fields: Title, Message area, Action Button.
Alert Dialog code has three methods:
setTitle() method for displaying the Alert Dialog box Title
setMessage() method for displaying the message
setIcon() method is use to set the icon on Alert dialog box.
Then we add the two Button, setPositiveButton and setNegativeButton to our Alert Dialog Box as shown
below.
Example:
Below are the steps for Creating the Alert Dialog Android Application:
Step 1: Create a new project. After that, you have java and XML file.
Step 2: Open your XML file and then add TextView for message as shown below (you can change it
accordingly).
Step 3: Now, open up the activity java file. After, on create method declaration, the onbackpressed
method is called when you click the back button of your device.
Step 4: Create the object of Builder class Using AlertDialog.Builder. Now, set the Title, message.
Step 5: In a builder object set the positive Button now gives the button name and add the OnClickListener
of DialogInterface. Same as with the negative Button, at last, create the Alert dialog Box with builder
object and then show the Alert Dialog.
Step 6: Now if positive button press finish the app goto outside from the app if negative then finish the
dialog box
Step 7: Now run it and then press the back button. After that click Yes or No Button.
Toast
In Android, Toast is used to display information for a period of time. It contains a message to be displayed
quickly and disappears after specified period of time. It does not block the user interaction. Toast is a subclass
of Object class. In this we use two constants for setting the duration for the Toast. Toast notification in android
always appears near the bottom of the screen. We can also create our custom toast by using custom
layout(xml file).
Note: In Android, Toast is used when we required to notify user about an operation without expecting any user
input. It displays a small popup for message and automatically fades out after timeout.
Important Methods Of Toast:
Let’s we discuss some important methods of Toast that may be called in order to manage the Toast.
1. makeText(Context context, CharSequence text, int duration): This method is used to initiate the Toast.
This method take three parameters First is for the application Context, Second is text message and last one is
duration for the Toast.
Constants of Toast: Below is the constants of Toast that are used for setting the duration for the Toast.
1. LENGTH_LONG: It is used to display the Toast for a long period of time. When we set this duration the
Toast will be displayed for a long duration.
2. LENGTH_SHORT: It is used to display the Toast for short period of time. When we set this duration the
Toast will be displayed for short duration.
Below we show the use of makeText() method of Toast in which we set application context, a text message and
duration for the Toast.
Toast toast = Toast.makeText(getApplicationContext(), "Simple Toast", Toast.LENGTH_LONG); // initiate the
Toast with context, message and duration for the Toast
2. show(): This method is used to display the Toast on the screen. This method is display the text which we
create using makeText() method of Toast.
Below we Firstly initiate the Toast and then display it using show() method.
Toast toast = Toast.makeText(getApplicationContext(), "Simple Toast In Android", Toast.LENGTH_LONG); //
initiate the Toast with context, message and duration for the Toast
toast.show(); // display the Toast
3. setGravity(int,int,int): This method is used to set the gravity for the Toast. This method accepts three
parameters: a Gravity constant, an x-position offset, and a y-position offset.
Below we Firstly initiate the Toast, set top and left gravity and then display it using show() method.
Toast toast = Toast.makeText(getApplicationContext(), "Simple Toast In Android", Toast.LENGTH_LONG); //
initiate the Toast with context, message and duration for the Toast
toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0); // set gravity for the Toast.
toast.show(); // display the Toast
4. setText(CharSequence s): This method is used to set the text for the Toast. If we use makeText() method
and then we want to change the text value for the Toast then we use this method.
Below we firstly create a new Toast using makeText() method and then set the text for the Toast.
Toast toast = Toast.makeText(getApplicationContext(), "Simple Toast In Android", Toast.LENGTH_LONG); //
initiate the Toast with context, message and duration for the Toast
toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0); // set gravity for the Toast.
toast.setText("Changed Toast Text"); // set the text for the Toast
toast.show(); // display the Toast
5. setDuration(int duration): This method is used to set the duration for the Toast. If we use makeText()
method and then we want to change the duration for the Toast then we use this method.
Below we firstly create a new Toast using makeText() method and then set the duration for the Toast.
Toast toast = Toast.makeText(getApplicationContext(), "Simple Toast In Android", Toast.LENGTH_LONG); //
initiate the Toast with context, message and duration for the Toast
toast.setGravity(Gravity.TOP | Gravity.LEFT, 0, 0); // set gravity for the Toast.
toast.setDuration(Toast.LENGTH_SHORT); // set the duration for the Toast.
toast.show(); // display the Toast
6. inflate(int, ViewGroup): This method is used to inflate the layout from the xml. In this method first
parameter is the layout resource ID and the second is the root View.
Below we retrieve the Layout Inflater and then inflate the layout from the xml file.
// Retrieve the Layout Inflater and inflate the layout from xml
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
7. setView(View): This method is used to set the view for the Toast. In this method we pass the inflated layout
which we inflate using inflate() method.
Below we firstly retrieve the layout inflater and then inflate the layout and finally create a new Toast and pass
the inflated layout in the setView() method.
// Retrieve the Layout Inflater and inflate the layout from xml
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.custom_toast_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
Popup
Android Popup Menu: Android Popup Menu displays a list of items in a vertical list which presents to the
view that invoked the menu and useful to provide an overflow of actions that related to specific content.
So in this article, we are going to discuss the Popup Menu. A PopupMenu displays a Menu in a popup
window anchored to a View. The popup will be shown below the anchored View if there is room(space)
otherwise above the View. If any IME(Input Method Editor) is visible the popup will not overlap it until the
View(to which the popup is anchored) is touched. Touching outside the popup window will dismiss it.
Example
In this example, we are going to make a popup menu anchored to a Button and on click, the popup menu will
appear, and on a touch of the popup menu item, a Toast message will be shown. A sample GIF is given below
to get an idea about what we are going to do in this article. Note that we are going to implement this project
using the Java language.
we will create a popup_menu file inside that menu resource directory. Go to app > res > menu > right-click
> New > Menu Resource File and create a menu resource file and name it as popup_menu. In the
popup_menu file, we will add menu items. Below is the code snippet for the popup_menu.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/java"
android:title="Java" />
<item
android:id="@+id/kotlin"
android:title="Kotlin" />
<item
android:id="@+id/android"
android:title="Android" />
<item
android:id="@+id/react_native"
android:title="React Native" />
</menu>
Fragments
A Fragment represents a reusable portion of your app's UI. A fragment defines and manages its own layout, has
its own lifecycle, and can handle its own input events. Fragments cannot live on their own--they must
be hosted by an activity or another fragment. The fragment’s view hierarchy becomes part of, or attaches to, the
host’s view hierarchy.
Modularity
Fragments introduce modularity and reusability into your activity’s UI by allowing you to divide the UI into
discrete chunks. Activities are an ideal place to put global elements around your app's user interface, such as a
navigation drawer. Conversely, fragments are better suited to define and manage the UI of a single screen or
portion of a screen.
Consider an app that responds to various screen sizes. On larger screens, the app should display a static
navigation drawer and a list in a grid layout. On smaller screens, the app should display a bottom navigation bar
and a list in a linear layout. Managing all of these variations in the activity can be unwieldy. Separating the
navigation elements from the content can make this process more manageable. The activity is then responsible
for displaying the correct navigation UI while the fragment displays the list with the proper layout.
Figure 1. Two versions of the same screen on different screen sizes. On the left, a large screen contains a
navigation drawer that is controlled by the activity and a grid list that is controlled by the fragment. On the
right, a small screen contains a bottom navigation bar that is controlled by the activity and a linear list that is
controlled by the fragment.
Dividing your UI into fragments makes it easier to modify your activity's appearance at runtime. While your
activity is in the STARTED lifecycle state or higher, fragments can be added, replaced, or removed. You can
keep a record of these changes in a back stack that is managed by the activity, allowing the changes to be
reversed.
You can use multiple instances of the same fragment class within the same activity, in multiple activities, or
even as a child of another fragment. With this in mind, you should only provide a fragment with the logic
necessary to manage its own UI. You should avoid depending on or manipulating one fragment from another.
Fragment lifecycle
Each Fragment instance has its own lifecycle. When a user navigates and interacts with your app, your
fragments transition through various states in their lifecycle as they are added, removed, and enter or exit the
screen.
To manage lifecycle, Fragment implements LifecycleOwner, exposing a Lifecycle object that you can access
through the getLifecycle() method.
Each possible Lifecycle state is represented in the Lifecycle.State enum.
INITIALIZED
CREATED
STARTED
RESUMED
DESTROYED
By building Fragment on top of Lifecycle, you can use the techniques and classes available for Handling
Lifecycles with Lifecycle-Aware Components. For example, you might display the device's location on the
screen using a lifecycle-aware component. This component could automatically start listening when the
fragment becomes active and stop when the fragment moves to an inactive state.
As an alternative to using a LifecycleObserver, the Fragment class includes callback methods that correspond to
each of the changes in a fragment's lifecycle. These
include onCreate(), onStart(), onResume(), onPause(), onStop(), and onDestroy().
A fragment's view has a separate Lifecycle that is managed independently from that of the fragment's Lifecycle.
Fragments maintain a LifecycleOwner for their view, which can be accessed
using getViewLifecycleOwner() or getViewLifecycleOwnerLiveData(). Having access to the
view's Lifecycle is useful for situations where a Lifecycle-aware component should only perform work while a
fragment's view exists, such as observing LiveData that is only meant to be displayed on the screen.
This topic discusses the Fragment lifecycle in detail, explaining some of the rules that determine a fragment's
lifecycle state and showing the relationship between the Lifecycle states and the fragment lifecycle callbacks.
Fragments and the fragment manager
When a fragment is instantiated, it begins in the INITIALIZED state. For a fragment to transition through the
rest of its lifecycle, it must be added to a FragmentManager. The FragmentManager is responsible for
determining what state its fragment should be in and then moving them into that state.
Beyond the fragment lifecycle, FragmentManager is also responsible for attaching fragments to their host
activity and detaching them when the fragment is no longer in use. The Fragment class has two callback
methods, onAttach() and onDetach(), that you can override to perform work when either of these events occur.
The onAttach() callback is invoked when the fragment has been added to a FragmentManager and is attached to
its host activity. At this point, the fragment is active, and the Fragment Manager is managing its lifecycle state.
At this point, Fragment Manager methods such as find FragmentById() return this fragment.
onAttach() is always called before any Lifecycle state changes.
The onDetach() callback is invoked when the fragment has been removed from a FragmentManager and is
detached from its host activity. The fragment is no longer active and can no longer be retrieved
using findFragmentById().
onDetach() is always called after any Lifecycle state changes.
Note that these callbacks are unrelated to the Fragment Transaction methods attach() and detach(). For more
information on these methods, see Fragment transactions.
Create a fragment
A fragment represents a modular portion of the user interface within an activity. A fragment has its own
lifecycle, receives its own input events, and you can add or remove fragments while the containing activity is
running.
This document describes how to create a fragment and include it in an activity.
Setup your environment
Fragments require a dependency on the AndroidX Fragment library. You need to add the Google Maven
repository to your project's build.gradle file in order to include this dependency.
GroovyKotlin
buildscript {
...
repositories {
google()
...
}
}
allprojects {
repositories {
google()
...
}
}
To include the AndroidX Fragment library to your project, add the following dependencies in your
app's build.gradle file:
GroovyKotlin
dependencies {
def fragment_version = "1.3.5"
The Fragment library also provides more specialized fragment base classes:
DialogFragment
Displays a floating dialog. Using this class to create a dialog is a good alternative to using the dialog
helper methods in the Activity class, as fragments automatically handle the creation and cleanup of
the Dialog. See Displaying dialogs with DialogFragment for more details.
PreferenceFragmentCompat
Displays a hierarchy of Preference objects as a list. You can use PreferenceFragmentCompat to create a
settings screen for your app.
Add a fragment to an activity
Generally, your fragment must be embedded within an AndroidX FragmentActivity to contribute a portion of
UI to that activity's layout. FragmentActivity is the base class for AppCompatActivity, so if you're already
subclassing AppCompatActivity to provide backward compatibility in your app, then you do not need to change
your activity base class.
You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's
layout file or by defining a fragment container in your activity's layout file and then programmatically adding
the fragment from within your activity. In either case, you need to add a FragmentContainerView that defines
the location where the fragment should be placed within the activity's view hierarchy. It is strongly
recommended to always use a FragmentContainerView as the container for fragments,
as FragmentContainerView includes fixes specific to fragments that other view groups such as FrameLayout do
not provide.
Add a fragment via XML
To declaratively add a fragment to your activity layout's XML, use a FragmentContainerView element.
Here's an example activity layout containing a single FragmentContainerView:
<!-- res/layout/example_activity.xml -->
<androidx.fragment.app.FragmentContainerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.example.ExampleFragment" />
The android:name attribute specifies the class name of the Fragment to instantiate. When the activity's layout is
inflated, the specified fragment is instantiated, onInflate() is called on the newly instantiated fragment, and
a FragmentTransaction is created to add the fragment to the FragmentManager.
To provide your users a familiar experience, use material's most common UX patterns:
Promote your UI's main action with a Floating Action Button (FAB).
Show your brand, navigation, search, and other actions with the App Bar.
Show and hide your app's navigation with the Navigation Drawer.
Use one of many other material components for your app layout and navigation, such as collapsing toolbars,
tabs, a bottom nav bar, and more. To see them all, check out the Material Components for Android catalog
And whenever possible, use predefined material icons. For example, the navigation "menu" button for your
navigation drawer should use the standard "hamburger" icon. See Material Design Icons for a list of available
icons. You can also import SVG icons from the material icon library with Android Studio's Vector Asset
Studio.
Elevation shadows and cards
In addition to the X and Y properties, views in Android have a Z property. This new property represents the
elevation of a view, which determines:
The size of the shadow: views with higher Z values cast bigger shadows.
The drawing order: views with higher Z values appear on top of other views.
Elevation is often applied when your layout includes a card-based layout, which helps you display important
pieces of information inside cards that provide a material look. You can use the CardView widget to create
cards with a default elevation. For more information, see Create a Card-Based Layout.
For information about adding elevation to other views, see Create Shadows and Clip Views.
Animations
The new animation APIs let you create custom animations for touch feedback in UI controls, changes in view
state, and activity transitions.
These APIs let you:
Respond to touch events in your views with touch feedback animations.
Hide and show views with circular reveal animations.
Switch between activities with custom activity transition animations.
Create more natural animations with curved motion.
Animate changes in one or more view properties with view state change animations.
Show animations in state list drawables between view state changes.
Touch feedback animations are built into several standard views, such as buttons. The new APIs let you
customize these animations and add them to your custom views.
For more information, see Animations Overview.
To learn more about how to design a floating action button into your app according to the Material Design
Guidelines, also see Buttons: Floating Action Button.
Figure 1. A floating action button
By default, the FAB is colored by the colorAccent attribute, which you can customize with the theme's color
palette.
You can configure other FAB properties using either XML attributes or corresponding methods, such as the
following:
The size of the FAB, using the app:fabSize attribute or the setSize() method.
The ripple color of the FAB, using the app:rippleColor attribute or the setRippleColor() method.
The FAB icon, using the android:src attribute or the setImageDrawable() method.
Respond to button taps
You can then apply an View.OnClickListener to handle FAB taps. For example, the following code displays
a Snackbar when the user taps the FAB:
KotlinJava
val fab: View = findViewById(R.id.fab)
fab.setOnClickListener { view ->
Snackbar.make(view, "Here's a Snackbar", Snackbar.LENGTH_LONG)
.setAction("Action", null)
.show()
}
Navigation
The Navigation is a powerful component in Android Development which provide easy access to destinations in
your app. If you’ve come to this article, you probably know that and considering the title of the story, you’ve
probably implemented it before.
But since I want to help developers with different backgrounds and experiences, I would like to make this tutorial
in three parts, and that is because at the time of writing this, I passed by a number of different articles
implementing the Navigation Drawer in a number of different ways. So the three parts of the tutorial are really
just:
1. An easy approach to implementing Navigation Drawer (I do not claim this, so feel free to let me know if
there’s an even easier approach ), and
2. Applying custom styles to the Navigation Drawer.
3. Adding header view to the Navigation Drawer and styling it.
The navigation drawer is the most common feature offered by android and the navigation drawer is a UI panel
that shows your app’s main navigation menu. It is also one of the important UI elements, which provides
actions preferable to the users like example changing user profile, changing settings of the application, etc. In
this article, it has been discussed step by step to implement the navigation drawer in android.
The navigation drawer slides in from the left and contains the navigation destinations for the app.
The user can view the navigation drawer when the user swipes a finger from the left edge of the activity.
They can also find it from the home activity by tapping the app icon in the action bar. The drawer icon is
displayed on all top-level destinations that use a DrawerLayout. Have a look at the following image to get an
idea about the Navigation drawer.