0% found this document useful (0 votes)
27 views40 pages

Android UNIT 2

Uploaded by

jassim qazi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views40 pages

Android UNIT 2

Uploaded by

jassim qazi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 40

UNIT 2

Services
Service is a component that is used to perform operations on the
background such as downloading files, playing music, handle network
transactions, etc. It doesn't have any UI (user interface). The main aim of a
service is to ensure that the application remains active in the background so
that the user can operate multiple applications at the same time. A service can
run continuously in the background even if the application is closed or the user
switches to another application.

Types of Android Services

Foreground Service:
 A foreground service is used for tasks that are noticeable to the user
and should be given higher priority. Foreground services provide
ongoing notifications to keep the user aware of the ongoing
operation such as playing music, tracking location, and performing
tasks that require ongoing user interaction.
Background Service:
 A background service is used for tasks that are less noticeable to the
user and can run silently without showing a persistent notification.
 Background services are typically used for tasks like background data
synchronization, updating databases, and performing periodic tasks.
Bound Service
A Bound Service in Android is a type of service that enables various
components within an app, such as activities, to establish connections with
it. This service continues to perform its designated tasks as long as any of
these app components are connected to it. Multiple components can
connect to and interact with a bound service simultaneously. To establish a
connection between an app component and a bound service, the
bindService() method is utilized. This type of service is particularly
suitable for scenarios where ongoing communication and interaction
between app components and a service are required.

The Life Cycle of Android Services

In android, services has 2 possible paths to complete its life cycle


namely Started and Bounded.
1). Started Service (Unbounded Service):
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) Bound Service
A service is bound when another component (e.g. client) calls bindService() method.
The client can unbind the service by calling the unbindService() method.
The service cannot be stopped until all clients unbind the service.

1 onStartCommand()
The system calls this method when another component, such as an activity,
requests that the service be started, by calling startService(). If you implement this
method, it is your responsibility to stop the service when its work is done, by
calling stopSelf() or stopService() methods.

2 onCreate()
The system calls this method when the service is first created
using onStartCommand() or onBind(). This call is required to perform one-time set-
up.

3
onBind()
The system calls this method when another component wants to bind with the
service by calling bindService(). If you implement this method, you must provide an
interface that clients use to communicate with the service, by returning
an IBinder object. You must always implement this method, but if you don't want to
allow binding, then you should return null.

4
onUnbind()
The system calls this method when all clients have disconnected from a particular
interface published by the service.

5
onRebind()
The system calls this method when new clients have connected to the service, after
it had previously been notified that all had disconnected in its onUnbind(Intent).

6
onDestroy()
The system calls this method when the service is no longer used and is being
destroyed. Your service should implement this to clean up any resources such as
threads, registered listeners, receivers, etc.

Example

Activity_main.java

package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this,"In onstart",Toast.LENGTH_SHORT).show();
Log.i("Info","In oncreate");
}
@Override
protected void onStart(){
super.onStart();
Toast.makeText(this,"In onStart",Toast.LENGTH_SHORT).show();
Log.i("Info","In onStart");
}
@Override
protected void onResume(){
super.onResume();
Toast.makeText(this,"In onResume",Toast.LENGTH_SHORT).show();
Log.i("Info","In onResume");
}
@Override
protected void onPause(){
super.onPause();
Toast.makeText(this,"In onPause",Toast.LENGTH_SHORT).show();
Log.i("Info","In onPause");
}
@Override
protected void onStop(){
super.onStop();
Toast.makeText(this,"In onStop",Toast.LENGTH_SHORT).show();
Log.i("Info","In onStop");
}
@Override
protected void onDestroy(){
super.onDestroy();
Toast.makeText(this,"In onDestroy",Toast.LENGTH_SHORT).show();
Log.i("Info","In onDestroy");
}
}

BROADCAST RECIEVER
A Broadcast Receiver in Android is a mechanism that enables your app to listen and
respond to messages or events sent by the system or other apps. It acts like a listener
that gets triggered when specific things happen, allowing your app to perform actions
or display information in response to those events. Broadcast receivers are commonly
used to respond to system events, such as network changes, battery level changes,
incoming SMS messages, etc. They can also be used to listen for custom broadcasts sent
within your app or even between different apps.

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.
We can receive a broadcast by registering broadcasts using an android application manifest file
(AndroidManifest.xml). We need to specify <receiver> element in apps manifest file like as shown
below.

<receiver android:name=".SampleBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>

Example

XML

<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout

xmlns:android="http://schemas.android.com/apk/res/androi
d"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context=".MainActivity">

</androidx.constraintlayout.widget.ConstraintLayout>

Main.java
import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

AirplaneModeChangeReceiver airplaneModeChangeReceiver = new


AirplaneModeChangeReceiver();

@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);
}
}

Create a new class

Below is the code for the AirplaneModeChangeReceiver file.


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.provider.Settings;
import android.widget.Toast;

public class AirplaneModeChangeReceiver extends BroadcastReceiver {

@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();
}
}

private static boolean isAirplaneModeOn(Context context) {


return Settings.System.getInt(context.getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON, 0) != 0;
}
}
Content Providers
Content Providers are a very important component that serves the purpose of a
relational database to store the data of applications. The role of the content
provider in the android system is like a central repository in which data of the
applications are stored, and it facilitates other applications to securely access
and modifies that data based on the user requirements. Android system allows
the content provider to store the application data in several ways. Users can
manage to store the application data like images, audio, videos, and personal
contact information by storing them in SQLite Database, in files, or even on a
network. In order to share the data, content providers have certain permissions
that are used to grant or restrict the rights to other applications to interfere with
the data. Content Providers allow different apps to share data in a controlled manner. Content
Providers are typically accessed using URIs. A URI specifies the data to be accessed and the
desired operation (e.g., querying, inserting, updating, or deleting data).
Creating a Content Provider
Following are the steps which are essential to follow in order to create a
Content Provider:
 Create a class in the same directory where the that MainActivity file resides
and this class must extend the ContentProvider base class.
 To access the content, define a content provider URI address.
 Create a database to store the application data.
 Implement the six abstract methods of ContentProvider class.
 Register the content provider in AndroidManifest.xml file using <provider>
tag.
Following are the six abstract methods and their description which are
essential to override as the part of ContenProvider class:
Abstract
Method Description

A method that accepts arguments and fetches the data from the
query()
desired table. Data is retired as a cursor object.

To insert a new row in the database of the content provider.


insert()
It returns the content URI of the inserted row.
Abstract
Method Description

This method is used to update the fields of an existing row.


update()
It returns the number of rows updated.

This method is used to delete the existing rows.


delete()
It returns the number of rows deleted.

This method returns the Multipurpose Internet Mail


Extension(MIME)
getType()
type of data to the given Content URI.

As the content provider is created, the android system calls


onCreate()
this method immediately to initialise the provider.

FORM WIDGETS
Form widgets are components that allow users to input data or make selections. These widgets
are used to create interactive forms where users can provide information like text, numbers,
dates, and more. Here are some common form widgets in Android programming:

1. EditText: This widget is used for single-line or multi-line text input. It's commonly used
for fields like names, emails, passwords, etc.
2. TextView: While not a traditional form widget for user input, TextViews are often used
to display labels or instructions next to input fields.
3. Button: Buttons are used to trigger actions, like submitting a form or initiating a search.
4. RadioButton: RadioButton widgets are used for single-choice selections in a group.
Users can select one option out of a list.
5. CheckBox: CheckBoxes allow users to select multiple options from a list. Each checkbox
represents an independent choice.
6. Spinner: Spinners provide a dropdown list of choices. Users can select one option from
the list.
7. DatePicker: DatePicker allows users to select dates from a calendar. It's often used for
birthdates, appointment scheduling, etc.
8. TimePicker: TimePicker allows users to select a specific time, usually for tasks like
setting alarms or reminders.
9. SeekBar: SeekBar widgets let users select a value from a continuous range, often for
things like volume control or brightness adjustments.
10. Switch: Switches are used for binary choices, like turning a setting on or off.
11. AutoCompleteTextView: This widget provides suggestions while users type, which can
help with quickly entering information.
12. RatingBar: RatingBars allow users to rate something on a scale, such as a product or
service.

TEXT FIELDS
Text fields are input fields that allow users to enter text. The primary widget used for
text input is the EditText widget. Here's how you can work with text fields in Android
programming:

1. Creating an EditText in XML Layout:


In your XML layout file (e.g., activity_main.xml), you can define an EditText widget
like this:
XML
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text here"
android:inputType="text" />
1. In this example, android:hint sets a placeholder text, and android:inputType
specifies the type of input expected (text in this case).
2. Accessing EditText in Java/Kotlin:
In your activity's Java/Kotlin code, you can access the EditText widget using its ID and
perform actions on it. For example:
JAVA
EditText editText = findViewById(R.id.editText);
String userText = editText.getText().toString();

TEXT VIEW
TextView is a simple widget that is seen in every android application.
This widget is used to display simple text within the android
application. We can add custom styling to the text that we have to
show
ATTRIBUTES OF TEXT VIEW
android:id: This attribute is used to assign a unique identifier to the TextView element, which
can be referenced in your Java or Kotlin code.

android:text: It sets the text content that will be displayed by the TextView.

android:textSize: This attribute controls the size of the text in the TextView.

android:textColor: It specifies the color of the text.

android:textStyle: You can use this attribute to make the text bold, italic, or normal.

android:layout_width and android:layout_height: These attributes specify the width


and height of the TextView.

LAYOUTS
Layouts are used to define the structure and arrangement of user interface components
within an app's user interface. They determine how different widgets, views, and
elements are positioned and displayed on the screen. Android provides various layout
types to help you design your app's user interface effectively. Here are some common
layout types:

1. LinearLayout: LinearLayout is the most basic layout in android programming,


that aligns all the child views or widgets either in a horizontal manner or a
vertical manner by specifying the android:orientation attribute. If one
applies android:orientation=”vertical” then elements will be arranged one
after another in a vertical manner and If you
apply android:orientation=”horizontal” then elements will be arranged one
after another in a horizontal manner.
EXAMPLE
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
</LinearLayout>

ATTRIBUTES OF LINEAR LAYOUT

android:id
This is the ID which uniquely identifies the layout.

android:layout_width and android:layout_height: These attributes


specify the width and height of the LinearLayout. You can use values like
wrap_content, match_parent, or specific dimensions.

android:orientation: This attribute determines the orientation of child


views within the LinearLayout. You can set it to either "horizontal" or
"vertical".

android:gravity: It sets the gravity of the child views within the


LinearLayout. This attribute affects the alignment of child views within the
layout.

2. RelativeLayout:
RelativeLayout allows you to position child views relative to each other or the parent
container. It's useful when you want to create complex layouts with views placed in
relation to one another. Using RelativeLayout, you can align two
elements by right border, or make one below another, centered in
the screen, centered left, and so on. By default, all child views are
drawn at the top-left of the layout
ATTRIBUTES OF REALTIVE LAYOUT
android:id: This attribute is used to assign a unique identifier to the RelativeLayout,
which can be referenced in your Java or Kotlin code.

android:layout_width and android:layout_height: These attributes specify the width


and height of the RelativeLayout. You can use values like wrap_content,
match_parent, or specific dimensions.

android:layout_alignParentStart/End/Top/Bottom: These attributes are used to align


a child view with the start, end, top, or bottom of the parent RelativeLayout.
android:layout_centerHorizontal/Vertical: These attributes are used to center a child
view horizontally or vertically within the RelativeLayout.

android:layout_toLeftOf/toRightOf: These attributes are used to position a child view


to the left or right of another view within the RelativeLayout.
3. ConstraintLayout:
 ConstraintLayout is a more flexible and powerful layout .
With the help of
ConstraintLayout, we can position our UI components in any sort of order
whether it may be horizontal or vertical. ConstraintLayout, can control the
group of widgets through a single line of code.
Important Attributes of ConstraintLayout
Attributes Description

This is used to give a unique id to the


android:id
layout.

This is used to constrain the view with


app:layout_constraintBottom_toBottomOf
respect to the bottom position.

This attribute is used to constrain the view


app:layout_constraintLeft_toLeftOf
with respect to the left position.

This attribute is used to constrain the view


app:layout_constraintRight_toRightOf
with respect to the right position.
Attributes Description

This attribute is used to constrain the view


app:layout_constraintTop_toTopOf
with respect to the top position.

Advantages of using ConstraintLayout in Android


 ConstraintLayout provides you the ability to completely design your UI with
the drag and drop feature provided by the Android Studio design editor.
 It helps to improve the UI performance over other layouts.
 With the help of ConstraintLayout, we can control the group of widgets
through a single line of code.
 With the help of ConstraintLayout, we can easily add animations to the UI
components which we used in our app.
Disadvantages of using ConstraintLayout
 When we use the Constraint Layout in our app, the XML code generated
becomes a bit difficult to understand.
 In most of the cases, the result obtain will not be the same as we got to see
in the design editor.
 Sometimes we have to create a separate layout file for handling the UI for
the landscape mode.
How ConstraintLayout differs from RelativeLayout?
 In Constraint Layout, we have to add constraints to the view on all four sides
whereas in Relative Layout we can simply align our UI component relative to
its ID using the ids of UI components.
 In Relative Layout, the UI which is actually seen in the Design editor of
Android Studio will be the same as that we will get to see in the app, but in
the case of Constraint layout if the UI component is not Constrained then the
UI will not look same as that of in design editor.

4. FrameLayout: FrameLayout is a simple layout that allows you to stack multiple


child views on top of each other. It's commonly used for simple overlays or
layering.
attributes of frame layout
1. android:id: This attribute is used to assign a unique identifier to the FrameLayout,
which can be referenced in your Java or Kotlin code.
2.
android:layout_width and android:layout_height: These attributes specify the width
and height of the FrameLayout. You can use values like wrap_content, match_parent,
or specific dimensions.

android:foreground: This attribute allows you to set a drawable or color to appear in


front of the child views.
android:layout_gravity: This attribute determines how the child views within the
FrameLayout are positioned within the parent layout.
android:padding and android:paddingStart/paddingEnd: These attributes set
padding for the FrameLayout to control the space around its content.
5. GridLayout: GridLayout arranges its child views in a grid format with rows and
columns. It's useful for creating uniform layouts, such as grids of images or icons.
Attributes of grid layout
1. android:id: This attribute is used to assign a unique identifier to the GridLayout, which
can be referenced in your Java or Kotlin code.
2.
android:layout_width and android:layout_height: These attributes specify the width
and height of the GridLayout. You can use values like wrap_content, match_parent, or
specific dimensions.
3.
android:rowCount and android:columnCount: These attributes define the number of
rows and columns in the grid.
4.
android:layout_gravity: This attribute specifies how the GridLayout itself is positioned
within its parent layout.
5.
android:padding and android:paddingStart/paddingEnd: These attributes set
padding for the GridLayout to control the space around its content.

BUTTON CONTROLS
buttons are a fundamental user interface element that users can interact with to trigger actions
or perform tasks in your app.

In your Javacode, you can access the button using its ID and set up a click listener to perform
actions when the button is clicked:

Button myButton = findViewById(R.id.myButton);


myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Code to execute when the button is clicked
}
});
1. Button Attributes:
Buttons have various attributes you can customize:
 android:text: Sets the text displayed on the button.
 android:drawableLeft, android:drawableRight, etc.: Allows you to place icons
or drawables next to the button text.
 android:onClick: Specifies a method in your activity that will be called when the
button is clicked. This approach doesn't require explicit click listeners in your
code.
 android:background: Sets the background drawable of the button.
 android:enabled: Determines if the button is clickable and responsive to user
interaction.
2. Button States:
Buttons have different visual states (pressed, focused, enabled, etc.). You can define
different drawables for each state to give visual feedback to users when interacting with
the button.
3. Styling Buttons:
You can apply custom styles to buttons using XML resources. This includes changing
colors, text appearance, background, and more.
4. Button Types:
Android offers different types of buttons, such as Button (the standard button),
ImageButton (a button with an image), and ToggleButton (a button that toggles
between two states).

Here's a simple example of how you might create a button and handle its click event:

Xm
<Button
android:id="@+id/myButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />

JAVA
Button myButton = findViewById(R.id.myButton);
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Perform an action when the button is clicked
Toast.makeText(MainActivity.this, "Button Clicked!",
Toast.LENGTH_SHORT).show();
}
});

TOGGLE BUTTONS

Toggle buttons, also known as switch buttons, are UI elements that allow users to switch
between two states, usually represented by "on" and "off" or "enabled" and "disabled".

Adding a ToggleButton to Your Layout:


You can add a toggle button to your XML layout file using the <ToggleButton>
element:

XML
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toggle" />
1. Toggle Attributes:
Toggle buttons have various attributes you can customize:
 android:textOn: Text to display when the toggle is in the "on" state.
 android:textOff: Text to display when the toggle is in the "off" state.
 android:checked: Determines the initial state of the toggle.
2. Styling Toggle Buttons:
You can apply custom styles to toggle buttons using XML resources, just like with other
UI elements.
Here's a simple example of how you might create a toggle button and handle its state changes:

XML

<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="On"
android:textOff="Off" />
JAVA
ToggleButton toggleButton = findViewById(R.id.toggleButton);
toggleButton.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked) {
if (isChecked) {
// Perform an action when the toggle is switched on
Toast.makeText(MainActivity.this, "Toggle On",
Toast.LENGTH_SHORT).show();
} else {
// Perform an action when the toggle is switched off
Toast.makeText(MainActivity.this, "Toggle Off",
Toast.LENGTH_SHORT).show();
}
}
});

SPINNERS
a Spinner is a user interface element that provides a dropdown list of selectable items. It's
similar to a combo box in other programming frameworks. Users can tap on a Spinner to reveal
the available options and select one. Touching the spinner displays a drop down menu with all
other available values, from which the user can select a new one. Android spinner is associated
with AdapterView. So we need to set the adapter class with the Spinner. Here's how you can
work with Spinners:

Adding a Spinner to Your Layout:


You can add a Spinner to your XML layout file using the <Spinner> element:
XML
<Spinner
android:id="@+id/simpleSpinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Main.Java file

package example.abhiandriod.spinnerexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity implements


AdapterView.OnItemSelectedListener{

String[] Fruits={"Apple","orange","Banana","Mango","Cherry"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Getting the instance of Spinner and applying OnItemSelectedListener on it
Spinner spin = (Spinner) findViewById(R.id.simpleSpinner);
spin.setOnItemSelectedListener(this);

//Creating the ArrayAdapter instance having the bank name list


ArrayAdapter aa = new ArrayAdapter(this,android.R.layout.simple_spinner_item,Fruits);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spin.setAdapter(aa);
}
}
}

OPTION MENU
An options menu provides a set of actions that users can access by tapping on the
"options" button or icon in the app's toolbar. The options menu is typically used to
provide common actions that are relevant to the current context of the app.

HOW TO CREATE AN OPTION MENU


1. Create a new Android project or use an existing one.
2. In your res/menu directory, create a new XML file named menu_main.xml

Menu.main.xml
<menu
<item
android:id="@+id/item1"
android:title="Item 1"
app:showAsAction="never" />

<item
android:id="@+id/item2"
android:title="Item 2"
app:showAsAction="never" />

<item
android:id="@+id/item3"
android:title="Item 3"
app:showAsAction="never"
<menu>
<item androidid:”@+id/subitem1”
android:title:=”Sub item1”/>
<item androidid:”@+id/subitem2”
android:title:=”Sub item2”/>
</menu>
</item>
</menu>
Now code for mainactivity.java
package com.example.menu;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu,menu);
return true;
}
}

CONTEXT MENU
A context menu is a floating menu that appears when the user performs a long-click (also known
as a "contextual" or "context" click) on an element. such as a button, list item, or image. Context
menus are used to provide options related to the selected view or the context of the long press.

HOW TO CREATE A CONTEXT MENU


Here's a simple Android program that demonstrates how to create a context menu with
three items: "Edit," "Delete," and "Share."

1. Create a new Android project or use an existing one.


2. In your activity's layout XML file (e.g., activity_main.xml), add a view element that you
want to associate with the context menu. For example, let's use a TextView:
<TextView
android:id="@+id/contextTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Long press me for options"
android:layout_centerInParent="true"/>
4. In your res/menu directory, create a new XML file named context_menu.xml with the
following content:
<menu
<item
android:id="@+id/context_edit"
android:title="Edit" />
<item
android:id="@+id/context_delete"
android:title="Delete" />
<item
android:id="@+id/context_share"
android:title="Share" />
</menu>

Mainactivity.java
package com.example.menu;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

private TextView contextTextView;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

contextTextView = findViewById(R.id.contextTextView);
registerForContextMenu(contextTextView);
}

@Override
public boolean onCreateContextMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu,menu);
return true;
}

Sub-Menu

Sub menu is basically list of menus inside a menu option. So, sub-menus can
also be called as nested menus. Submenus are used to organize and group menu items,
making it easier for users to access and understand the available options.

HOW TO CREATE A SUB MENU

1. Create a new Android project or use an existing one.


2. In your activity's layout XML file (e.g., activity_main.xml), add a TextView to the
layout (this is just for demonstration purposes):
<TextView

android:id="@+id/textView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Tap for options"

android:layout_centerInParent="true"/>

4. In your res/menu directory, create a new XML file named submenu.xml with the
following content:

Menu.main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/item1"
android:title="Item 1"
app:showAsAction="never" />
<item
android:id="@+id/item2"
android:title="Item 2"
app:showAsAction="never" />

<item
android:id="@+id/item3"
android:title="Item 3"
app:showAsAction="never"
<menu>
<item androidid:”@+id/subitem1”
android:title:=”Sub item1”/>
<item androidid:”@+id/subitem2”
android:title:=”Sub item2”/>
</menu>
</item>

</menu>
MainActivity.java
package com.example.menu;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu,menu);
return true;
}
}

IMAGES AND MEDIA


In Android programming, you can work with images and media to enhance the visual
and auditory aspects of your app. Here are some common tasks and concepts related to
handling images and media in Android:

1. Displaying Images:
To display images in your app, you can use the ImageView widget. You can set the
image using a drawable resource or a bitmap. Here's an example:
<ImageView

android:id="@+id/imageView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:src="@drawable/my_image" />

1. In this example, replace @drawable/my_image with the actual resource ID of your image.
2. Loading Images Efficiently:
When working with images, it's important to load them efficiently to avoid memory
issues. You can use libraries like Picasso, Glide, or Coil to help manage image loading,
caching, and resizing.

EXAMPLE FOR CREATING IMAGES AND MEDIA

If we want to add an image we have to copy the name of that image and paste it into the
drawable section res/drawable

1. Create a new Android project or use an existing one.


2. Add an image file (e.g., my_image.jpg) to the res/drawable directory of your project.
3. Add an audio file (e.g., my_audio.mp3) to the res/raw directory of your project.
4. In your activity's layout XML file (e.g., activity_main.xml), add an ImageView and a
Button for playing audio:
XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:id="@+id/container"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingLeft="16dp"

android:paddingTop="16dp"

android:paddingRight="16dp"

android:paddingBottom="16dp"

tools:context=".MainActivity">

<ImageView

android:id="@+id/imageView"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:src="@drawable/my_image"

android:layout_centerInParent="true" />

<Button

android:id="@+id/playButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Play Audio"

android:layout_below="@id/imageView"

android:layout_centerHorizontal="true" />
</RelativeLayout>

MAINACTIVITY.JAVA

import android.media.MediaPlayer;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

private MediaPlayer mediaPlayer;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

// Initialize MediaPlayer

mediaPlayer = MediaPlayer.create(this, R.raw.my_audio);

Button playButton = findViewById(R.id.playButton);

playButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Play the audio

mediaPlayer.start();
}

});

@Override

protected void onDestroy() {

super.onDestroy();

// Release the MediaPlayer when the activity is destroyed

if (mediaPlayer != null) {

mediaPlayer.release();

mediaPlayer = null;

ALERT DIALOUGE
an AlertDialog is a common user interface component that displays a small window with a title,
message, and optional buttons. AlertDialogs are used to present information, confirm actions,
and prompt the user for input

You can create an AlertDialog using the AlertDialog.Builder class.

You can customize the appearance and behavior of the AlertDialog further by adding custom
views, changing button styles, and more.

HOW TO CREATE AN ALERT DIALOUGE BOX

Here's a simple Android program that demonstrates how to create and display an
AlertDialog with a title, message, and "OK" button:

1. Create a new Android project or use an existing one.


IN YOUR XML FILE ADD A BUTTON
<Button

android:id="@+id/showAlertButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Show Alert"

android:layout_centerInParent="true"/>

mainactivity.java
import android.app.AlertDialog;

import android.content.DialogInterface;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button showAlertButton = findViewById(R.id.showAlertButton);

showAlertButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Create and show the AlertDialog

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);


builder.setTitle("Alert")

.setMessage("This is a simple AlertDialog example.")

.setPositiveButton("OK", new DialogInterface.OnClickListener() {

public void onClick(DialogInterface dialog, int which) {

// Handle OK button click

dialog.dismiss(); // Close the dialog

})

.show();

});

TOAST
Toast is a lightweight notification that provides a simple way to display short messages or
notifications to the user. Toasts appear at the bottom of the screen and are typically used to
convey information that doesn't require the user's immediate attention. They automatically
disappear after a short period of time.

We can create a toast for short duration with the help of

Toast.makeText(getApplicationContext(), "This is a short Toast message",


Toast.LENGTH_SHORT).show();

We can create a toast for long duration with the help of

Toast.makeText(getApplicationContext(), "This is a long Toast message",


Toast.LENGTH_LONG).show();

Here's a simple Android program that demonstrates how to use a Toast to display short
messages to the user:

1. Create a new Android project or use an existing one.


2. In your activity's layout XML file (e.g., activity_main.xml), add a Button:
<Button

android:id="@+id/showToastButton"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Show Toast"

android:layout_centerInParent="true"/>

1. In your activity class (usually MainActivity.java or similar), implement the Toast


functionality:

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button showToastButton = findViewById(R.id.showToastButton);

showToastButton.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {

// Show a short duration Toast message


Toast.makeText(MainActivity.this, "This is a Toast message",
Toast.LENGTH_SHORT).show();

});

POP UP
, a "pop-up" typically refers to a graphical user interface element that appears on top of
the main content or screen, often used for displaying additional information, options, or
user interactions. There are several ways to implement pop-ups in Android:

1. AlertDialogs: AlertDialogs are a common type of pop-up used to display important


messages, confirmation dialogs, or user prompts. You can customize them with titles,
messages, buttons, and even custom views.
2. PopupMenu: The PopupMenu class is used to create pop-up menus that appear when
the user taps on a specific view. They usually contain options related to the tapped view.
You can use PopupMenu with the PopupMenu.OnMenuItemClickListener interface to
handle item selections.
3. BottomSheetDialog: A BottomSheetDialog is a pop-up that appears from the bottom
of the screen, often used to display additional actions, filters, or other content. It can be
implemented as a modal or persistent bottom sheet.
4. Custom Dialogs: You can create custom pop-ups by extending the Dialog class or
using the DialogFragment class. This allows you to design your own pop-up layout and
behavior.
5. Toast: While not a traditional pop-up, toasts can be considered a form of brief pop-up
notification that appears at the bottom of the screen and disappears after a short
duration.
EXAMPLE
4. In your activity's layout XML file (e.g., activity_main.xml), add a Button to trigger the
pop-up:

<Button
android:id="@+id/showPopupButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Show Pop-up"
android:layout_centerInParent="true"/>
in the res/layout directory. Add the desired UI elements to this layout. In this example, we'll
create a layout with a TextView and a Button:

<!-- res/layout/popup_layout.xml -->


<LinearLayout

xmlns:android="http://schemas.android.com/apk/res/androi
d"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="16dp">

<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is a custom pop-up" />

<Button
android:id="@+id/closeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Close" />
</LinearLayout>
3. In your activity class (usually MainActivity.java or similar), implement the pop-up
functionality:

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button showPopupButton =
findViewById(R.id.showPopupButton);
showPopupButton.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
// Create a custom layout inflater
LayoutInflater inflater =
LayoutInflater.from(MainActivity.this);
View popupView =
inflater.inflate(R.layout.popup_layout, null);

// Build and show the AlertDialog with the custom


layout
AlertDialog.Builder builder = new
AlertDialog.Builder(MainActivity.this);
builder.setView(popupView)
.setCancelable(false) // Prevent dismissal by
tapping outside
.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss(); // Close the dialog
}
});

AlertDialog alertDialog = builder.create();


alertDialog.show();

// Close button click listener inside the custom


layout
Button closeButton =
popupView.findViewById(R.id.closeButton);
closeButton.setOnClickListener(new
View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss(); // Close the dialog
}
});
}
});
}
}

You might also like