Android Menu
Android Menu
Navigation
Navigation refers to the interactions that allow users to navigate across, into, and back out
from the different pieces of content within your app. Android Jetpack's Navigation
component helps you implement navigation, from simple button clicks to more complex
patterns, such as app bars and the navigation drawer. The Navigation component also
ensures a consistent and predictable user experience by adhering to an established set of
principles.
The Navigation component consists of three key parts that are described below:
As you navigate through your app, you tell the NavController that you want to navigate
either along a specific path in your navigation graph or directly to a specific destination.
The NavController then shows the appropriate destination in the NavHost.
The Navigation component provides a number of other benefits, including the following:
Back-button navigation
Back-button navigation—navigation back through the history of screens—is deeply rooted
in the Android system. Android users expect the Back button in the bottom left corner of
every screen to take them to the previous screen. The set of historical screens always starts
with the user's Launcher (the device's Home screen), as shown in the figure below. Pressing
Back enough times should return the user back to the Launcher.
You don't have to manage the Back button in your app. The system handles tasks and the
back stack—the list of previous screens—automatically. The Back button by default simply
traverses this list of screens, removing the current screen from the list as the user presses it.
There are, however, cases where you may want to override the behavior for the Back
button. For example, if your screen contains an embedded web browser in which users can
interact with page elements to navigate between web pages, you may wish to trigger the
embedded browser's default back behavior when users press the device's Back button.
The onBackPressed() method of the Activity class is called whenever the activity detects the
user's press of the Back key. The default implementation simply finishes the current
activity, but you can override this to do something else:
@Override
public void onBackPressed() {
// Add the Back key handler here.
return;
}
If your code triggers an embedded browser with its own behavior for the Back key, you
should return the Back key behavior to the system's default behavior if the user uses the
Back key to go beyond the beginning of the browser's internal history.
You can enable the user to navigate up to and down from a parent, and sideways among
siblings:
● Descendant navigation: Navigating down from a parent screen to a child screen.
● Ancestral navigation: Navigating up from a child screen to a parent screen.
● Lateral navigation: Navigating from one sibling to another sibling (at the same
level).
You can use a main activity (as a parent screen) and then other activities or fragments to
implement a hierarchy of screens within an app.
RecyclerView
RecyclerView makes it easy to efficiently display large sets of data. You supply the data and
define how each item looks, and the RecyclerView library dynamically creates the elements
when they're needed.
As the name implies, RecyclerView recycles those individual elements. When an item scrolls
off the screen, RecyclerView doesn't destroy its view. Instead, RecyclerView reuses the view
for new items that have scrolled onscreen. RecyclerView improves performance and your
app's responsiveness, and it reduces power consumption.
Note: RecyclerView is the name of both the class and the library that contains it. On this page,
RecyclerView in code font always means the class in the RecyclerView library.
Key classes
Several classes work together to build your dynamic list.
● RecyclerView is the ViewGroup that contains the views corresponding to your data.
It's a view itself, so you add RecyclerView to your layout the way you would add any
other UI element.
● Each individual element in the list is defined by a view holder object. When the view
holder is created, it doesn't have any data associated with it. After the view holder is
created, the RecyclerView binds it to its data. You define the view holder by
extending RecyclerView.ViewHolder.
● The RecyclerView requests views, and binds the views to their data, by calling
methods in the adapter. You define the adapter by extending RecyclerView.Adapter.
● The layout manager arranges the individual elements in your list. You can use one of
the layout managers provided by the RecyclerView library, or you can define your
own. Layout managers are all based on the library's LayoutManager abstract class.
1. Decide how the list or grid looks. Ordinarily, you can use one of the RecyclerView
library's standard layout managers.
2. Design how each element in the list looks and behaves. Based on this design, extend
the ViewHolder class. Your version of ViewHolder provides all the functionality for
your list items. Your view holder is a wrapper around a View, and that view is
managed by RecyclerView.
3. Define the Adapter that associates your data with the ViewHolder views.
You also need to design the layout of the individual items. You need this layout when you
design the view holder, as described in the next section.
When you define your adapter, you override three key methods:
Here's a typical example of a simple adapter with a nested ViewHolder that displays a list
of data. In this case, the RecyclerView displays a simple list of text elements. The adapter is
passed an array of strings containing the text for the ViewHolder elements.
Generally, the style is a combination of multiple attributes such as background color, font color, font size, font
style, height, width, padding, margin, etc. and it is used to change the look and feel of View or window.
In android, the style is defined in a separate XML resource file and we can use that defined style for the
Views in XML that specifies the layout. The Styles in android are similar to CSS styles in web design.
Following is the example of defining a TextView control with required style attributes in an XML layout file.
<TextView
android:id="@+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#86AD33"
android:textSize="20dp"
android:textStyle="bold" />
If you observe above code snippet, we defined a TextView control with required style attributes directly in
XML layout file.
Suppose if we use same or similar TextView styles in multiple places of our application, then the duplication
of code will increase and in future, if we want to change the style of our application, we need to update the
same style in all the places and it’s a time-consuming process.
We can overcome this problem by defining a style for the particular view and use the same style in all the
places wherever it is required in our application.
If we use style attribute we can move all style attributes related to particular view to a separate XML
resource file and refer that file in XML layout like shown below
<TextView
android:id="@+id/txtResult"
style="@style/TextviewStyle"/>
If you observe above code snippet, we removed all style attributes from XML layout and moved those
attributes to a style definition called TextviewStyle. In following sections we will see the definition of
TextviewStyle attribute.
In android, theme is a style that is applied to an entire activity or app, instead of an individual View like as
mentioned above. When we applied a style as a theme, the views in activity or app apply to the all style
attributes that supports. For example. If we apply TextviewStyle as a theme for an activity, then the text of all
the views in activity appears in the same style.
In simple words, if we use an entry from a resource file to style a view, then we can call it a style. In case if we
use an entry from a resource file to style activity or app, then we can call it a theme.
As we discussed, we need to define a style in a separate XML resource file and use that defined style for the
Views in XML that specifies the layout.
To define a set of styles, we need to create a new XML file in /res/values directory of our project and the root
node of XML file must be a <resources>.
To create a style in the XML file, we need to follow the below steps.
● We need to add <style> element in the XML file with a name attribute to uniquely identify the style.
● To define attributes of style, we need to add an <item> elements with a name that defines a style
attribute and we need to add appropriate value to each <item> element.
In android, we can define multiple styles using <style> element with a name attribute to uniquely identify the
style in an XML file.
Following is the example of defining a style in separate XML file using <style> element.
<resources>
<style name="TextviewStyle">
<item name="android:textColor">#86AD33</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">20dp</item>
<item name="android:padding">10dp</item>
</style>
</resources>
If you observe above code snippet, we created a style “TextviewStyle” with all required style attributes and
we can use same style for multiple views instead of writing the same code multiple times.
Once we are done with the creation of style, we can use it for the views which are defined in the XML layout
file with style attribute.
Following is the example of setting a style for the views in the XML layout.
<TextView
android:id="@+id/txtResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="@style/TextviewStyle"
android:text="Welcome to Tutlane"/>
If you observe above code snippet, the style (TextviewStyle) whatever we defined in XML is applied to
TextView control using style attribute and we can use the same style for other TextView’s also based on our
requirements.
Android Style Inheritance
In android, by using parent attribute in <style> element we can inherit the properties from an existing style
and define only the attributes that we want to change or add. We can inherit the styles that we created
ourselves or from the styles that are built into the platform.
Following is the example to inherit the android platform’s default TextView style
(@android:style/Widget.TextView) and modify it.
<item name="android:textColor">#86AD33</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">20dp</item>
</style>
If you observe above code snippet, we are inheriting built-in platform style Widget.TextView using parent
attribute in <style> element.
In android, we can inherit the styles that we defined our self. To inherit our styles we don’t need to use parent
attribute instead, we can use dot notation by prefixing the name of the style that we want to inherit to the
name of our new style, separated by a period.
Following is the example of inheriting the style (TextviewStyle) which we defined above and create a new style
like as shown below.
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#86AD33</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">20dp</item>
<item name="android:layout_marginTop">12dp</item>
<item name="android:layout_marginLeft">100dp</item>
</style>
<style name="TextviewStyle.Blue">
<item name="android:textColor">#0088CC</item>
<item name="android:textStyle">italic</item>
</style>
If you observe above code snippet, we didn’t used any parent attribute in <style> tag, we used style name
TextviewStyle to inherit all the style attributes. The TextviewStyle.Blue style will inherit all the properties
from TextviewStyle and overrides the android:textColor and android:textStyle attributes to make the text
italic and Blue. The newly created style referenced from Textview as @style/TextviewStyle.Blue.
We can continue inheriting the styles like this as many times by chaining names with periods.
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#86AD33</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">20dp</item>
<item name="android:layout_marginTop">12dp</item>
<item name="android:layout_marginLeft">100dp</item>
</style>
<style name="TextviewStyle.Blue">
<item name="android:textColor">#0088CC</item>
<item name="android:textStyle">italic</item>
</style>
<style name="TextviewStyle.Blue.Background">
<item name="android:background">#FBBC09</item>
</style>
The TextviewStyle.Blue.Background style will inherit the properties from TextviewStyle and
TextviewStyle.Blue styles and it will add a new android:background attribute.
Android Defining Themes
In android, theme is a style that is applied to an entire activity or app, instead of an individual View like as
mentioned above. When we applied a style as a theme, the views in activity or app apply to the all style
attributes that supports. For example. If we apply TextviewStyle as a theme for an activity, then the text of all
the views in activity appears in the same style.
<color name="custom_theme_color">#b0b0ff</color>
<item name="android:windowBackground">@color/custom_theme_color</item>
<item name="android:colorBackground">@color/custom_theme_color</item>
</style>
To set a theme for a particular activity, open AndroidManifest.xml file and write the code like as shown
below
<activity android:theme="@android:style/CustomTheme">
In case, if we want to set the theme for all the activities in android application, open AndroidManifest.xml file
and write the code like as shown below.
<application android:theme="@android:style/CustomTheme">
In android, we can customize the application basic theme colors based on our requirements.
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
We can customize the application basic theme colors based on our requirements. Now we will see how to use
these styles and themes in android applications with examples.
Create a new android application using android studio and give names as StylesThemesExample. In case if
you are not aware of creating an app in android studio check this article Android Hello World App.
Now we need to define our styles in styles.xml file, for that open styles.xml file from \res\values folder and
write the code like as shown below.
styles.xml
<resources>
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
<item name="android:layout_width">wrap_content</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">100dp</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:textColor">#86AD33</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">20dp</item>
</style>
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_marginLeft">100dp</item>
<item name="android:layout_marginTop">10dp</item>
<item name="android:textColor">#FFFFFF</item>
<item name="android:background">#F1511B</item>
<item name="android:textStyle">bold</item>
<item name="android:textSize">15dp</item>
</style>
</resources>
If you observe above code, we defined a two styles (TextViewStyle, ButtonStyle) and we can apply these styles
for required controls in android application.
Now open an activity_main.xml file from \res\layout path and write the code like as shown below
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="@+id/TextView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="100dp"
android:layout_marginTop="200dp"
android:textColor="#00ADEF"
android:textSize="15dp"
android:text="@string/wlcmsg"/>
<TextView
android:id="@+id/TextView2"
style="@style/TextviewStyle"
android:text="Welcome to Tutlane"/>
<Button
android:id="@+id/btnShow"
android:text="Click on Button"
style="@style/ButtonStyle" />
</LinearLayout>
Material Design Components (MDC Android) offers designers and developers a way
to implement Material Design in their Android application. Developed by a core
team of engineers and UX designers at Google, these components enable a reliable
development workflow to build beautiful and functional Android applications.
Material design in Android is one of the key features that attracts and engages the
customer towards the application. This is a special type of design, which is guided by
Google. So in this article, it has been introduced to the basic things that need to be
considered before designing or developing any Materialistic Android Application.
The topics covered in these articles are
1. Color and theming
2. Typography (Choosing the right font)
3. Material design components
4. Shaping the material design components
1. Colors and Theming
By choosing the right kind of color combination reflects the application’s brand and
style. For example, the application’s main or primary color is the Green, then in the
whole application, the green color will be frequently shown. Choosing the color for
the application, there are three types of colors to be chosen for developing the
android application.
● Primary Color: This color should be chosen very cautiously because this
color is frequently visible in the application components like high
emphasis buttons or the button ripple color, and also the top and bottom
navigation bar.
● Secondary Color: This color should be chosen only when there is a low
complexity level of the application. This color will be applied to those
elements which need a little color accent like the. background color for the
Floating Action Buttons (FAB), sliders, toggle buttons, chips (Active
State), progress bars, etc.
● Light and Dark variants: These colors are the variants of the primary
color. The dark variant of the primary color is set for the status bar and
the light variant of the primary color is set for the Floating action button,
outline for the edit texts, and where the elements need some color accents
the light variant of the primary colors will be set for them. Have a look at
the following image when only the primary color is set for the application
theme looks like.
But according to the complexity of the application, there are various types of color
can be chosen.
● Have a look at the following image, having selected the primary color, with
that the Complementary color can be chosen or Analogous color can be
chosen or Triadic color can be chosen or Secondary color can be chosen to
meet the required style.
There are several ways to do background processing in Android. Two of those ways are:
In most situations the Loader framework is a better choice, but it's important to know how
AsyncTask works.
Note: The Loader framework provides special-purpose classes that manage loading and
reloading updated data asynchronously in the background. You learn more about loaders
in a later lesson.
In this chapter you learn why it's important to process some tasks in the background, off
the UI thread. You learn how to use AsyncTask, when not to use AsyncTask, and the basics of
using loaders.
The UI thread
When an Android app starts, it creates the main thread, which is often called the UI thread.
The UI thread dispatches events to the appropriate user interface (UI) widgets. The UI
thread is where your app interacts with components from the Android UI toolkit
(components from the android.widget and android.view packages).
The UI thread needs to give its attention to drawing the UI and keeping the app responsive
to user input. If everything happened on the UI thread, long operations such as network
access or database queries could block the whole UI. From the user's perspective, the app
would appear to hang. Even worse, if the UI thread were blocked for more than a few
seconds (about 5 seconds currently) the user would be presented with the "application not
responding" (ANR) dialog. The user might decide to quit your app and uninstall it.
Conversely, don't use a background thread to manipulate your UI, because the Android UI
toolkit is not thread-safe.
AsyncTask
A worker thread is any thread which is not the main or UI thread. Use the AsyncTask class to
implement an asynchronous, long-running task on a worker thread. AsyncTask allows you to
perform background operations on a worker thread and publish results on the UI thread
without needing to directly manipulate threads or handlers.
1. onPreExecute() is invoked on the UI thread before the task is executed. This step is
normally used to set up the task, for instance by showing a progress bar in the UI.
2. doInBackground(Params...) is invoked on the background thread immediately after
onPreExecute() finishes. This step performs a background computation, returns a
result, and passes the result to onPostExecute(). The doInBackground() method can also
call publishProgress(Progress...) to publish one or more units of progress.
3. onProgressUpdate(Progress...) runs on the UI thread after publishProgress(Progress...) is
invoked. Use onProgressUpdate() to report any form of progress to the UI thread while
the background computation is executing. For instance, you can use it to pass the
data to animate a progress bar or show logs in a text field.
4. onPostExecute(Result) runs on the UI thread after the background computation has
finished. The result of the background computation is passed to this method as a
parameter.
For complete details on these methods, see the AsyncTask reference. Below is a diagram of
their calling order.
AsyncTask usage
To use the AsyncTask class, define a subclass of AsyncTask that overrides the
doInBackground(Params...) method (and usually the onPostExecute(Result) method as well). This
section describes the parameters and usage of AsyncTask, then shows a complete example.
AsyncTask parameters
In your subclass of AsyncTask, provide the data types for three kinds of parameters:
● The "Params" parameter type is String, which means that MyAsyncTask takes one or
more strings as parameters in doInBackground(), for example to use in a query.
● The "Progress" parameter type is Void, which means that MyAsyncTask won't use the
publishProgress() or onProgressUpdate() methods.
Android lets your application connect to the internet or any other local network and allows
you to perform network operations.
A device can have various types of network connections. This chapter focuses on using
either a Wi-Fi or a mobile network connection.
Sr.No State
1 Connecting
2 Disconnected
3 Disconnecting
4 Suspended
5 Unknown
InputStream is = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
String webPage = "",data="";
1
disconnect()
This method releases this connection so that its resources may be either reused or
closed
2
getRequestMethod()
This method returns the request method which will be used to make the request
to the remote HTTP server
3
getResponseCode()
This method returns response code returned by the remote HTTP server
4
setRequestMethod(String method)
This method Sets the request command which will be sent to the remote HTTP
server
5
usingProxy()
This method returns whether this connection uses a proxy server or not
Example
The below example demonstrates the use of HttpURLConnection class. It creates a basic
application that allows you to download HTML from a given web page.
To experiment with this example, you need to run this on an actual device on which wifi
internet is connected .
Broadcast Receivers
Broadcast in android is the system-wide events that can occur when the device
starts, when a message is received on the device or when incoming calls are received,
or when a device goes to airplane mode, etc. Broadcast Receivers are used to
respond to these system-wide events. Broadcast Receivers allow us to register for the
system and application events, and when that event happens, then the register
receivers get notified. There are mainly two types of Broadcast Receivers:
● Static Broadcast Receivers: These types of Receivers are declared in the
manifest file and works even if the app is closed.
● Dynamic Broadcast Receivers: These types of receivers work only if the
app is active or minimized.
Since from API Level 26, most of the broadcast can only be caught by the dynamic
receiver, so we have implemented dynamic receivers in our sample project given
below. There are some static fields defined in the Intent class which can be used to
broadcast different events. We have taken a change of airplane mode as a broadcast
event, but there are many events for which broadcast register can be used.
Following are some of the important system-wide generated intents:-
The two main things that we have to do in order to use the broadcast receiver in our
application are:
Creating the Broadcast Receiver:
class AirplaneModeChangeReceiver:BroadcastReceiver() {
Registering a BroadcastReceiver:
IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED).also {
registerReceiver(receiver,it)
Example
Below is the sample project showing how to create the broadcast Receiver and how
to register them for a particular event and how to use them in the application.
● Java
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onStart() {
super.onStart();
IntentFilter filter = new
IntentFilter(Intent.ACTION_AIRPLANE_MODE_CHANGED);
registerReceiver(airplaneModeChangeReceiver, filter);
}
@Override
protected void onStop() {
super.onStop();
unregisterReceiver(airplaneModeChangeReceiver);
}
}
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.widget.Toast;
@Override
public void onReceive(Context context, Intent intent) {
if (isAirplaneModeOn(context.getApplicationContext())) {
Toast.makeText(context, "AirPlane mode is on",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(context, "AirPlane mode is off",
Toast.LENGTH_SHORT).show();
}
}
Output:
1. Foreground Services:
Services that notify the user about its ongoing operations are termed as Foreground
Services. Users can interact with the service by the notifications provided about the
ongoing task. Such as in downloading a file, the user can keep track of the progress
in downloading and can also pause and resume the process.
2. Background Services:
Background services do not require any user intervention. These services do not
notify the user about ongoing background tasks and users also cannot access them.
The process like schedule syncing of data or storing of data fall under this service.
3. Bound Services:
This type of android service allows the components of the application like activity to
bound themselves with it. Bound services perform their task as long as any
application component is bound to it. More than one component is allowed to bind
themselves with a service at a time. In order to bind an application component with
a service bindService() method is used.
In android, services have 2 possible paths to complete its life cycle namely Started
and Bounded.
By following this path, a service will initiate when an application component calls
the startService() method. Once initiated, the service can run continuously in the
background even if the component is destroyed which was responsible for the start
of the service. Two option are available to stop the execution of service:
● By calling stopService() method,
● The service can stop itself by using stopSelf() method.
2. Bounded Service:
A user-defined service can be created through a normal class which is extending the
class Service. Further, to carry out the operations of service on applications, there
are certain callback methods which are needed to be overridden. The following are
some of the important methods of Android Services:
Methods Description
onStartCommand
()
requests to start a service using startService(). Once the
service is started,
it can be stopped explicitly using stopService() or
stopSelf() methods.
onUnbind()
onRebind()
onCreate()
onDestroy()
Android Notification
Android Notification provides short, timely information about the action happened in the
application, even it is not running. The notification displays the icon, title and some amount
of the content text.