Professional Documents
Culture Documents
Page 1 of 45
APPLICATION CONTEXT
What is Context in Android?
The Circumstances that form the setting for an Event, Statement, or Idea, and in
terms of which it can be fully understood.
Looking at this definition we come across two things:
The Context tells us about the surrounding information.
It is very important to understand the environment which we want to
understand.
We can break the Context and its use into three major points:
It allows us to access resources.
It allows us to interact with other Android components by sending
messages.
It gives you information about your app environment.
Types of Context in Android
There are mainly two types of Context that are available in Android.
1. Application Context
2. Activity Context
Application Context:
This Context is tied to the Lifecycle of an Application. Mainly it is an instance
that is a singleton and can be accessed via getApplicationContext(). Some use
cases of Application Context are:
If it is necessary to create a singleton object
During the necessity of a library in an activity
getApplicationContext():
It is used to return the Context which is linked to the Application which holds all
activities running inside it. When we call a method or a constructor, we often have
to pass a Context and often we use “this” to pass the activity Context
or “getApplicationContext” to pass the application Context. This method is
generally used for the application level and can be used to refer to all the
activities. For example, if we want to access a variable throughout the android
app, one has to use it via getApplicationContext()
Page 2 of 45
Example:
Inside the activity class, set the name and email of GlobalExampleClass, which
can be accessed from another activity. Let us see via the below steps.
Syntax:
// Activity 1
public class <your activity1> extends Activity {
........
........
private <yourapplicationname> globarVar;
........
@Override
public void onCreate(Bundle savedInstanceState) {
.......
final GlobalExampleClass globalExampleVariable =
(GlobalExampleClass) getApplicationContext();
Page 3 of 45
// In this activity set name and email and can reuse in other
activities
globalExampleVariable.setName("getApplicationContext example");
globalExampleVariable.setEmail("xxxxxx@gmail.com");
.......
}
// Activity 2
public class <your activity2> extends Activity {
........
........
private <yourapplicationname> globarVar;
.......
@Override
public void onCreate(Bundle savedInstanceState) {
.......
final GlobalExampleClass globalExampleVariable =
(GlobalExampleClass) getApplicationContext();
.......
}
So, whenever the variable scope is required throughout the application, we can
get it by means of getApplicationContext(). Following is a list of functionalities
of Application Context.
List of functionalities of Application Context:
Load Resource Values
Start a Service
Page 4 of 45
Bind to a Service
Send a Broadcast
Register BroadcastReceiver
Android Intent
Android Intent is the message that is passed between components such as activities,
content providers, broadcast receivers, services etc.
It is generally used with startActivity() method to invoke activity, broadcast receivers etc.
The dictionary meaning of intent is intention or purpose. So, it can be described as the
intention to do action.
1) Implicit Intent
2) Explicit Intent
1) Implicit Intent
Implicit Intent doesn't specifiy the component. In such case, intent provides information
of available components provided by the system that is to be invoked.
Page 5 of 45
For example, you may write the following code to view the webpage.
Page 6 of 45
activity_main.xml
Page 7 of 45
MainActivity.java
Output:
Page 8 of 45
2) Explicit Intent
Explicit Intent specifies the component. In such case, intent provides the external class
to be invoked.
Ex activity_main.xml
Page 9 of 45
activity_main.xml
Page 10 of 45
MainActivityOne.java
Page 11 of 45
activitytwo_main.xml
Page 12 of 45
MainActivityTwo.java
Page 13 of 45
Page 14 of 45
Android Activity Lifecycle:
Android Activity Lifecycle is controlled by 7 methods of android.app.Activity class. The
android Activity is the subclass of ContextThemeWrapper class.
By the help of activity, you can place all your UI components or widgets in a single screen.
The 7 lifecycle method of Activity describes how activity will behave at different states.
Page 15 of 45
Page 16 of 45
Page 17 of 45
Android Activity Lifecycle Example
It provides the details about the invocation of life cycle methods of activity. In this
example, we are displaying the content on the logcat.
MainActivity.java
Page 18 of 45
activity_main.xml
Output:
You will not see any output on the emulator or device. You need to open logcat.
Page 19 of 45
Now see on the logcat: onCreate, onStart and
onResume methods are invoked.
Now click on the HOME Button. You will see onPause method is invoked.
Page 20 of 45
After a while, you will see onStop method is invoked.
Now see on the emulator. It is on the home. Now click on the center button to launch the
app again.
Page 21 of 45
Now click on the lifecycleactivity icon.
Page 22 of 45
Now see on the logcat: onRestart, onStart and onResume methods are invoked.
Page 23 of 45
Now click on the back button. Now you will see onPause methods is invoked.
After a while, you will see onStop and onDestroy methods are invoked.
Page 24 of 45
Page 25 of 45
Multiple screen size
android:name="com.example.android.newsreader.HeadlinesFragment"
Page 27 of 45
android:layout_width="match_parent" />
</LinearLayout>
Use RelativeLayout
For example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/label"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Type here:"/>
<EditText
android:id="@+id/entry"
Page 28 of 45
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@id/label"/>
<Button
android:id="@+id/ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/entry"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:text="OK" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@id/ok"
android:layout_alignTop="@id/ok"
android:text="Cancel" />
</RelativeLayout>
There’s only so much mileage you can get from a flexible layout or
relative layout like the one in the previous sections. While those layouts
adapt to different screens by stretching the space within and around
components, they may not provide the best user experience for each
screen size. Therefore, your application should not only implement
flexible layouts, but should also provide several alternative layouts to
target different screen configurations. You do so by using configuration
qualifiers, which allows the runtime to automatically select the
appropriate resource based on the current device’s configuration (such
as a different layout design for different screen sizes).
For example, many applications implement the “two pane” pattern for
large screens (the app might show a list of items on one pane and the
Page 29 of 45
content on another pane). Tablets and TVs are large enough for both
panes to fit simultaneously on screen, but phone screens have to show
them separately. So, to implement these layouts, you could have the
following files:
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/andro
id"
android:orientation=”vertical”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>
<fragment android:id=”@+id/headlines”
android:layout_height=”fill_parent”
android:name=”com.example.android.newsreader.Headlines
Fragment”
android:layout_width=”match_parent” />
</LinearLayout>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/andro
id"
android:layout_width=”fill_parent”
android:layout_height=”fill_parent”
android:orientation=”horizontal”>
<fragment android:id=”@+id/headlines”
android:layout_height=”fill_parent”
Page 30 of 45
android:name=”com.example.android.newsreader.Headlines
Fragment”
android:layout_width=”400dp”
android:layout_marginRight=”10dp”/>
<fragment android:id=”@+id/article”
android:layout_height=”fill_parent”
android:name=”com.example.android.newsreader.ArticleFra
gment”
android:layout_width=”fill_parent” />
</LinearLayout>
Notice the large qualifier in the directory name of the second layout.
This layout will be selected on devices with screens classified as large
(for example, 7" tablets and above). The other layout (without qualifiers)
will be selected for smaller devices.
One of the difficulties developers had in pre-3.2 Android devices was the
“large” screen size bin, which encompasses the Dell Streak, the original
Galaxy Tab, and 7" tablets in general. However, many applications may
want to show different layouts for different devices in this category (such
as for 5" and 7" devices), even though they are all considered to be
“large” screens. That’s why Android introduced the “Smallest-width”
qualifier (amongst others) in Android 3.2.
Page 31 of 45
has a minimum width of 600 dp, so if you want your UI to have two
panes on those screens (but a single list on smaller screens), you can use
the same two layouts from the previous section for single and two-pane
layouts, but instead of the large size qualifier, use sw600dp to indicate the
two-pane layout is for screens on which the smallest-width is 600 dp.
Some layouts work well in both landscape and portrait orientations, but
most of them can benefit from adjustments. In the News Reader sample
app, here is how the layout behaves in each screen size and orientation:
Page 32 of 45
small screen, landscape: single pane, with logo
If you use simple images on components that can change size, you will
quickly notice that the results are somewhat less than impressive, since
the runtime will stretch or shrink your images uniformly. The solution
is using nine-patch bitmaps, which are specially formatted PNG files
that indicate which areas can and cannot be stretched.
Page 33 of 45
Form widgets
Form widgets are an essential part of any Android application
that requires user input. These widgets allow developers to
create forms that collect information from the user, such as login
details, contact information, or other types of data. In this article,
we will explore the various form widgets available in Android
Studio.
EditText:
EditText is a basic text field that allows users to input text or
numbers. It is one of the most commonly used form widgets in
Android applications. EditText can be used to collect all kinds of
user input, including email addresses, passwords, phone
numbers, and more. Developers can customize the appearance
of EditText by changing its background color, text color, hint text,
and more.
Spinner:
Spinner is a drop-down menu that allows users to select one item
from a list of options. It is used when the number of choices is
limited, and the options are predefined. Spinners are commonly
used for selecting countries, time zones, and other types of data
that can be represented as a list of options.
CheckBox:
CheckBox is a widget that allows users to select one or more
options from a list of choices. It is used when multiple options
need to be selected simultaneously. CheckBox is commonly
used for selecting interests, preferences, and other types of data
that require multiple selections.
RadioButton:
RadioButton is a widget that allows users to select one option
from a list of choices. It is used when only one option can be
Page 34 of 45
selected at a time. RadioButtons are commonly used for
selecting gender, payment methods, and other types of data that
require a single selection.
DatePicker:
DatePicker is a widget that allows users to select a date from a
calendar. It is used when collecting date-related information such
as birthdates, appointment dates, and other types of data that
require a specific date.
TimePicker:
TimePicker is a widget that allows users to select a time. It is
used when collecting time-related information such as
appointment times, deadlines, and other types of data that
require a specific time.
Text Fields
Text Fields are an important user interface element in Android
Studio that allow users to enter text-based information. Text
Fields can be used to collect a variety of user inputs such as
usernames, passwords, search queries, and other types of
textual data. In Android Studio, there are several types of Text
Fields that can be used depending on the type of data that needs
to be collected.
EditText:
EditText is the most basic Text Field in Android Studio. It allows
users to enter a single line of text or a multi-line text block.
Developers can customize the appearance of EditText by
Page 35 of 45
changing its background color, text color, hint text, and other
properties.
AutoCompleteTextView:
AutoCompleteTextView is a Text Field that provides suggestions
to the user as they type. It is used when the user is expected to
enter a value from a pre-defined set of options.
AutoCompleteTextView helps to reduce the amount of typing
required by the user and improve the accuracy of the input.
TextInputEditText:
TextInputEditText is an extension of the EditText widget that
provides additional functionality. It allows developers to add
labels, hints, and error messages to the Text Field.
TextInputEditText also supports validation of input, such as
checking for a valid email address or a minimum length
requirement.
SearchView:
SearchView is a Text Field that is used to collect search queries.
It allows users to enter a search term and submit it to a search
engine or search database. SearchView supports the display of
suggestions to the user as they type, which can help to refine
their search query.
PasswordEditText:
PasswordEditText is a Text Field that is used to collect
passwords. It provides the option to hide the input characters for
security purposes. PasswordEditText supports the display of a
"show password" button that allows users to temporarily reveal
the input characters.
1. LinearLayout:
LinearLayout is the simplest type of Layout in Android Studio. It
arranges UI components in a linear fashion either horizontally or
vertically. The UI components can be aligned to the left, right,
center, or to each other, giving the developer a lot of control over
the appearance of the Layout.
2. RelativeLayout:
RelativeLayout is a more complex type of Layout that allows the
developer to position UI components relative to each other. For
example, a UI component can be positioned above or below
another UI component or aligned to the left or right of another UI
component. This Layout is useful when creating complex UIs with
a lot of components.
3. ConstraintLayout:
ConstraintLayout is a powerful type of Layout that allows the
developer to create complex UIs with flexible dimensions. It is
used to define the position and size of UI components relative to
each other, using constraints. ConstraintLayout is highly
customizable, and it is widely used in modern Android
applications.
4. TableLayout:
Page 37 of 45
TableLayout is a type of Layout that arranges UI components in
a tabular format. It is used to create UIs with a grid-like
appearance. TableLayout is useful when dealing with data that
needs to be presented in a table format.
5. FrameLayout:
FrameLayout is a simple type of Layout that is used to display a
single UI component on the screen. This Layout is useful when
dealing with UI components that need to be displayed on top of
each other, such as when displaying images or videos.
Buttons
Buttons are one of the most commonly used UI components in Android
Studio, as they allow users to interact with an application by triggering
actions or events. Buttons are used to submit forms, navigate between
screens, initiate actions, and perform other functions. In this article, we
will explore the different types of Buttons available in Android Studio.
Standard Button:
The Standard Button is the most commonly used Button in
Android Studio. It has a rectangular shape and can be
customized with different colors, text, and styles. The onClick
listener is used to detect when the button is pressed and to trigger
the associated action.
ImageButton:
ImageButton is a Button that displays an image instead of text. It
is useful when the associated action is represented by an image,
Page 38 of 45
such as a camera icon for taking a picture. ImageButton can be
customized with different images and styles.
ToggleButton:
ToggleButton is a Button that can be in two states, on or off. It is
useful when the associated action requires a switch or toggle,
such as enabling or disabling a feature. ToggleButton can be
customized with different text and styles.
RadioButton:
RadioButton is a Button that is used in groups to provide a set of
mutually exclusive options. When one RadioButton is selected,
the others are automatically deselected. RadioButton is useful
when the associated action requires the selection of a single
option from a set of options.
CheckBox:
CheckBox is a Button that is used to select one or more options
from a set of options. Unlike RadioButton, CheckBox allows
multiple options to be selected simultaneously. CheckBox is
useful when the associated action requires the selection of
multiple options.
Toggle Button
Page 40 of 45
Android Spinner
Android Spinner is like the combox box of AWT or Swing. It can be
used to display the multiple options to the user in which only one
item can be selected by the user.
Android spinner is like the drop down menu with multiple values
from which the end user can select only one value.
Android spinner is associated with AdapterView. So you need to use
one of the adapter classes with spinner.
Android Spinner class is the subclass of AsbSpinner class.
A spinner is a type of drop-down list control in Android Studio that
allows users to select one value from a list of options. Spinners are
commonly used in forms and settings screens to present users with a set
of predefined options.
In Android Studio, a spinner can be created by adding a Spinner control
to a layout file and then defining its attributes in the XML code. The
options that are displayed in the spinner can be defined by adding an
array of values to the "android:entries" attribute of the Spinner control.
Spinners can be customized with different colors, styles, and animations
to fit the look and feel of an application. The default appearance of a
spinner is a rectangular box with a downward-facing arrow on the right-
hand side. When the user taps on the spinner, a drop-down list of options
is displayed, and the selected option is shown in the rectangular box.
In Android Studio, Spinners can be used in conjunction with listeners to
perform actions when an item is selected. The "OnItemSelectedListener"
interface can be used to detect when an item is selected and trigger an
action accordingly.
Spinners are an essential part of Android Studio that can help create user-
friendly interfaces for forms, settings screens, and other types of
applications. By using Spinners effectively, developers can improve the
user experience and make their applications more intuitive to use.
Page 41 of 45
Images are an important part of any Android application, and
Android Studio provides a variety of tools and resources for
working with images. Images are used to display visual content
such as icons, logos, photos, and other types of graphics.
images
In Android Studio, images can be added to an application in
several ways. One way is to add images to the "drawable" folder
of the project, which is a special folder where Android Studio looks
for images to use in the application. Images can also be added to
the project by importing them into the project using the "Import"
option.
Once images are added to the project, they can be used in various
ways. For example, they can be displayed in ImageViews, which
are special UI controls that are designed to display images.
ImageViews can be customized with different attributes such as
height, width, scale type, and more to fit the layout of the
application.
menu
Page 43 of 45
In Android Studio, menus can be created in two ways: the options
menu and the context menu. The options menu is a standard
menu that is displayed in the ActionBar, and it provides access to
common actions and settings. The context menu, on the other
hand, is a menu that is displayed when the user performs a long
press on a UI element, such as a button or a list item.
dialog
In Android Studio, a dialog is a small window that is displayed on
top of the current activity, typically to prompt the user for input or
to provide additional information. Dialogs are commonly used in
applications to display alerts, confirmations, and other types of
messages.
Page 44 of 45
of attributes and methods that can be used to customize its
appearance and behavior.
Page 45 of 45