Android Exam Final
Android Exam Final
The evolution of mobile software development began with the early feature phones that
only had basic functionalities like making calls and sending text messages. Over time,
feature phones evolved to include limited web browsing, games, and multimedia. The
real revolution began with the introduction of smartphones, which offered advanced
capabilities like touchscreens, powerful processors, and robust operating systems.
Key Milestones:
Key Points:
Linux Kernel: Core system services like security, memory management, and
process management.
Libraries: A set of C/C++ libraries used by various components of the Android
system.
Android Runtime (ART): Executes Dalvik bytecode compiled from Java/Kotlin
code.
Application Framework: Provides higher-level services to applications in the
form of Java classes.
Applications: User-facing applications written using the Android SDK.
Android SDK
The Android Software Development Kit (SDK) provides tools and libraries necessary for
developing Android applications. It includes a comprehensive set of development tools
such as:
Example:
AVD Manager: Allows developers to create and manage emulators for testing
applications on different Android versions and device configurations.
Building a First Android Application
Example:
MainActivity.java:
java
package com.example.myfirstapp;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
MyFirstApp/
├── app/
│ ├── build.gradle
│ ├── src/
│ │ ├── main/
│ │ │ ├── java/
│ │ │ │ └── com/example/myfirstapp/MainActivity.java
│ │ │ ├── res/
│ │ │ │ ├── layout/activity_main.xml
│ │ │ │ ├── values/strings.xml
│ │ │ └── AndroidManifest.xml
├── build.gradle
└── settings.gradle
Android Terminology
Context, Activity, Services, Intents
Diagram:
Tasks: Collections of activities that users interact with when performing a certain
job. Managed in a back stack, where each new activity is pushed onto the stack
and the back button pops activities off the stack.
Diagram:
Task Stack:
+--------------------+
| Activity 1 |
+--------------------+
| Activity 2 |
+--------------------+
| Activity 3 (top) |
+--------------------+
Android Activity Lifecycle
The activity lifecycle is a set of states that define how an activity transitions through its
different phases. Understanding this lifecycle is crucial for developing robust and
efficient Android applications.
1. onCreate(): This is the first method called when the activity is created. It's where
you initialize your activity, set up the user interface (UI), and allocate resources.
This method is called only once throughout the activity's lifecycle.
2. onStart(): This method is called when the activity becomes visible to the user. At
this point, the activity is visible but not in the foreground and not interacting with
the user.
3. onResume(): This method is called when the activity starts interacting with the
user. The activity is now in the foreground and at the top of the activity stack.
This is where the activity starts and resumes any paused UI updates, threads, or
processes.
4. onPause(): This method is called when the system is about to start another
activity. The current activity is still visible but partially obscured. You should stop
animations, save data, or release resources that don’t need to be kept alive.
5. onStop(): This method is called when the activity is no longer visible to the user.
The activity is now in the background, and you should release any resources that
are not needed while the activity is stopped.
6. onRestart(): This method is called when the activity in the stopped state is about
to be started again. This method is used to re-initialize resources that were
released in onStop().
7. onDestroy(): This method is called before the activity is destroyed. This is the
final call that the activity receives. It’s where you clean up resources and save
any persistent state.
8. onSaveInstanceState(): This method is called before the activity is destroyed to
save the activity state.
9. onRestoreInstanceState(): This method is called to restore the activity state
from a previously saved state.
Here is the Activity Lifecycle diagram:
+-----------+
| onCreate |
+-----+-----+
|
v
+-----+-----+
| onStart |
+-----+-----+
|
v
+-----+-----+
| onResume|
+-----+-----+
|
v
+-----+-----+
+-------- | onPause |
| +-----+-----+
| |
| v
| +-----+-----+
| +---| onStop |
| | +-----+-----+
| | |
| | v
| | +-----+-----+
| +---| onDestroy |
| +-----------+
|
+-----+
| | +-----------+
+-----+ | onRestart |
+-----+-----+
|
v
+-----+-----+
| onStart |
Example Code with Lifecycle Callbacks
MainActivity.java:
java
package com.example.lifecycleexample;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(TAG, "onCreate called");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart called");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume called");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause called");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop called");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart called");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy called");
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d(TAG, "onSaveInstanceState called");
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d(TAG, "onRestoreInstanceState called");
}
Intents are used to navigate between activities. They can be explicit (specifying the
target component) or implicit (specifying the action to be performed). Data can be
passed between activities using extras in intents.
Example:
MainActivity.java:
java
SecondActivity.java:
java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Example:
MyService.java:
java
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onDestroy() {
super.onDestroy();
// Clean up resources
}
}
java
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
Receiving and Broadcasting Intents
Example:
MyBroadcastReceiver.java:
java
xml
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
java
Intent intent = new Intent("com.example.CUSTOM_ACTION");
sendBroadcast(intent);
Example:
xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
Editing the manifest file using Eclipse (or Android Studio) provides a user-friendly GUI
interface, making it easier to add and modify elements without directly editing the XML
code.
Steps:
1. Open the Manifest File: In the Project Explorer, locate AndroidManifest.xml and
double-click to open it.
2. Use the Visual Editor: Switch to the Manifest tab at the bottom of the editor
window to use the visual editor.
3. Add Components: Use the GUI to add activities, services, permissions, and
other components by clicking on the appropriate sections and filling in the
required details.
Diagram:
Editing the manifest file manually involves directly modifying the XML code. This
approach provides more control and flexibility, especially for advanced configurations.
Example:
To declare a new activity manually, you would add the following to the application section
of AndroidManifest.xml:
xml
<activity android:name=".SecondActivity">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Managing Applications Identity and System Requirements
Example:
xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">
<application
android:versionCode="1"
android:versionName="1.0" >
...
</application>
</manifest>
Declaring Features:
Example:
xml
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-feature android:name="android.hardware.location.gps" android:required="false" />
Every activity in the application must be declared in the manifest file. This ensures the
Android system recognizes and can manage the activity.
Example:
xml
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Working with Permissions
Permissions protect sensitive data and system features. Applications must declare the
permissions they require in the manifest file.
Common Permissions:
Example:
xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Application resources are external files for strings, colors, dimensions, images,
animations, and menus. These resources are organized in the res directory.
Resource Types:
Example:
Strings:
xml
<!-- res/values/strings.xml -->
<resources>
<string name="app_name">MyApp</string>
<string name="welcome_message">Welcome to MyApp</string>
</resources>
Colors:
xml
<!-- res/values/colors.xml -->
<resources>
<color name="primary_color">#2196F3</color>
<color name="secondary_color">#FFEB3B</color>
</resources>
Dimensions:
xml
<!-- res/values/dimens.xml -->
<resources>
<dimen name="padding_small">8dp</dimen>
<dimen name="padding_large">16dp</dimen>
</resources>
Drawables:
xml
<!-- res/drawable/rounded_corners.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="8dp" />
<solid android:color="#2196F3" />
</shape>
Animations:
xml
<!-- res/anim/fade_in.xml -->
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="1000" />
</set>
Menus:
xml
<!-- res/menu/main_menu.xml -->
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_settings" android:title="Settings" />
<item android:id="@+id/action_about" android:title="About" />
</menu>
Working with Different Types of Resources
String Resources
String resources define text strings which can be localized for different languages.
Example:
xml
<!-- res/values/strings.xml -->
<resources>
<string name="app_name">MyApp</string>
<string name="welcome_message">Welcome to MyApp</string>
</resources>
Color Resources
Example:
xml
<!-- res/values/colors.xml -->
<resources>
<color name="primary_color">#2196F3</color>
<color name="secondary_color">#FFEB3B</color>
</resources>
Dimension Resources
Example:
xml
<!-- res/values/dimens.xml -->
<resources>
<dimen name="padding_small">8dp</dimen>
<dimen name="padding_large">16dp</dimen>
</resources>
Drawable Resources
Example:
xml
<!-- res/drawable/rounded_corners.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
<corners android:radius="8dp" />
<solid android:color="#2196F3" />
</shape>
Image Resources
Image resources include files like PNG and JPEG stored in the res/drawable directory.
Animation Resources
Example:
xml
<!-- res/anim/fade_in.xml -->
<set xmlns:android="http://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="1000" />
</set>
Menu Resources
Example:
xml
<!-- res/menu/main_menu.xml -->
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_settings" android:title="Settings" />
Android Views and Layouts
TextView
A TextView is a view that displays text to the user. It can be used to display static text or
to update text dynamically.
Example:
xml
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="18sp"
android:textColor="#000000" />
Spinner
A Spinner provides a dropdown list for selecting items. It is similar to a combo box in
other programming environments.
Example:
xml
<Spinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Java/Kotlin:
java
Spinner spinner = findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.spinner_items,
android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
Buttons
Buttons are interactive UI elements that users can click to perform actions.
Example:
xml
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
Java/Kotlin:
java
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Handle button click
}
});
Checkboxes and switches are toggle controls that can be checked or unchecked by the
user.
Example:
xml
<CheckBox
android:id="@+id/checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check Me" />
<Switch
android:id="@+id/switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Switch Me" />
Java/Kotlin:
java
CheckBox checkBox = findViewById(R.id.checkbox);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Handle checkbox state change
}
});
RadioGroups
A RadioGroup contains multiple radio buttons, allowing the user to select one option from
the group.
Example:
xml
<RadioGroup
android:id="@+id/radioGroup"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<RadioButton
android:id="@+id/radioButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 1" />
<RadioButton
android:id="@+id/radioButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Option 2" />
</RadioGroup>
Java/Kotlin:
java
RadioGroup radioGroup = findViewById(R.id.radioGroup);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// Handle radio button selection
}
});
ToggleButton
Example:
xml
<ToggleButton
android:id="@+id/toggleButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOff="OFF"
android:textOn="ON" />
Java/Kotlin:
java
ToggleButton toggleButton = findViewById(R.id.toggleButton);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Handle toggle button state change
}
});
Example:
xml
<DatePicker
android:id="@+id/datePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Java/Kotlin:
java
DatePicker datePicker = findViewById(R.id.datePicker);
TimePicker timePicker = findViewById(R.id.timePicker);
ProgressBar, SeekBar, RatingBar, Chronometer, and Clocks
These controls provide visual feedback and user interaction for various tasks.
Example:
xml
<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<SeekBar
android:id="@+id/seekBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<RatingBar
android:id="@+id/ratingBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Chronometer
android:id="@+id/chronometer"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<AnalogClock
android:id="@+id/analogClock"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<DigitalClock
android:id="@+id/digitalClock"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
Java/Kotlin:
java
ProgressBar progressBar = findViewById(R.id.progressBar);
SeekBar seekBar = findViewById(R.id.seekBar);
RatingBar ratingBar = findViewById(R.id.ratingBar);
Chronometer chronometer = findViewById(R.id.chronometer);
AnalogClock analogClock = findViewById(R.id.analogClock);
DigitalClock digitalClock = findViewById(R.id.digitalClock);
User Interfaces and Layouts
ViewGroups
ViewGroup is a special view that can contain other views (called children). It is the base
class for layouts and containers for views.
xml
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_gravity="bottom|end" />
</FrameLayout>
xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>
RelativeLayout: Positions views relative to each other.
xml
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_below="@id/textView" />
</RelativeLayout>
TableLayout
Example:
xml
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Row 1, Column 1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Row 1, Column 2" />
</TableRow>
<TableRow>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Row 2, Column 1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Row 2, Column 2" />
</TableRow>
</TableLayout>
GridLayout
Example:
xml
<GridLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:rowCount="2"
android:columnCount="2">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cell 1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cell 2" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cell 3" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Cell 4" />
</GridLayout>
Multiple Layouts on a Screen
You can nest multiple layouts to create complex user interfaces. This involves
combining different types of layouts like LinearLayout, RelativeLayout, and FrameLayout within
each other.
Example:
xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nested Layout Example" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button 2" />
</LinearLayout>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="match_parent"
android:layout_height="200dp"
android:src="@drawable/sample_image" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Overlay Text"
android:layout_gravity="center" />
</FrameLayout>
</LinearLayout>
Summary and Diagrams
Summary
Diagrams
|-----------------------|
| Hello, World! |
|-----------------------|
|-----------------------|
| |---Dropdown---| |
| | Item 1 | |
| | Item 2 | |
| | Item 3 | |
|-----------------------|
LinearLayout (vertical)
|
|--- TextView
| "Nested Layout Example"
|
|--- LinearLayout (horizontal)
| |--- Button "Button 1"
| |--- Button "Button 2"
|
|--- FrameLayout
|--- ImageView (with image)
|--- TextView "Overlay Text"
Data-Driven Containers
ListView: ListView is a view that displays a vertically scrollable list of items. Each item in
the list is defined by a layout that you can customize.
Example:
xml
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Java/Kotlin:
java
ListView listView = findViewById(R.id.listView);
String[] items = {"Item 1", "Item 2", "Item 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
Diagram:
+---------+
| ListView |
+---------+
| Item 1 |
+---------+
| Item 2 |
+---------+
| Item 3 |
+---------+
GridView: GridView is a view that displays items in a two-dimensional, scrollable grid.
Example:
xml
<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:numColumns="2" />
Java/Kotlin:
java
GridView gridView = findViewById(R.id.gridView);
String[] items = {"Item 1", "Item 2", "Item 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
gridView.setAdapter(adapter);
Diagram:
+---------+
| GridView |
+---------+
| Item 1 | Item 2 |
+---------+
| Item 3 |
+---------+
Example:
xml
<Gallery
android:id="@+id/gallery"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
Java/Kotlin:
java
Gallery gallery = findViewById(R.id.gallery);
Integer[] images = {R.drawable.image1, R.drawable.image2, R.drawable.image3};
ArrayAdapter<Integer> adapter = new ArrayAdapter<>(this, android.R.layout.simple_gallery_item,
images);
gallery.setAdapter(adapter);
Diagram:
+---------+
| Gallery |
+---------+
| Image 1 | Image 2 | Image 3 |
+---------+
Example:
java
String[] items = {"Item 1", "Item 2", "Item 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
Example:
java
Cursor cursor = database.query("table", null, null, null, null, null, null);
CursorAdapter adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, cursor,
new String[]{"column_name"}, new int[]{android.R.id.text1}, 0);
listView.setAdapter(adapter);
AdapterView: AdapterView is the base class for views that use an adapter to bind data.
Example:
java
AdapterView<Adapter> adapterView = findViewById(R.id.adapterView);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
adapterView.setAdapter(adapter);
ListActivity: ListActivity is an activity that includes a ListView.
Example:
java
public class MyListActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] items = {"Item 1", "Item 2", "Item 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
items);
setListAdapter(adapter);
}
}
Example:
java
public class MyTabActivity extends TabActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TabHost tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Tab 1").setContent(R.id.tab1));
tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("Tab 2").setContent(R.id.tab2));
}
}
Fragment Lifecycle
Fragments are modular sections of an activity's UI. They have their own lifecycle, which
is managed by the hosting activity.
Lifecycle Methods:
Diagram:
+--------------------+
| Fragment created |
+--------------------+
|
v
+--------------------+
| onAttach() |
+--------------------+
|
v
+--------------------+
| onCreate() |
+--------------------+
|
v
+--------------------+
| onCreateView() |
+--------------------+
|
v
+--------------------+
| onActivityCreated()|
+--------------------+
|
v
+--------------------+
| onStart() |
+--------------------+
|
v
+--------------------+
| onResume() |
+--------------------+
|
v
+--------------------+
| onPause() |
+--------------------+
|
v
+--------------------+
| onStop() |
+--------------------+
|
v
+--------------------+
| onDestroyView() |
+--------------------+
|
v
+--------------------+
| onDestroy() |
+--------------------+
|
v
+--------------------+
| onDetach() |
+--------------------+
List Fragment
Example:
java
public class MyListFragment extends ListFragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
String[] items = {"Item 1", "Item 2", "Item 3"};
ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
android.R.layout.simple_list_item_1, items);
setListAdapter(adapter);
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String selectedItem = (String) getListAdapter().getItem(position);
Toast.makeText(getActivity(), selectedItem, Toast.LENGTH_SHORT).show();
xml
<fragment
android:id="@+id/list_fragment"
android:name="com.example.MyListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent" />
WebView Fragment
A WebView fragment is a fragment that contains a WebView to display web content. This is
useful for embedding a web browser within your application.
Example: MyWebViewFragment.java:
java
public class MyWebViewFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_webview, container, false);
WebView webView = view.findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.example.com");
return view;
}
}
fragment_webview.xml:
xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Dialogs in Android are small windows that prompt the user to make a decision or enter
additional information. They are an essential part of user interaction in Android
applications.
Types of Dialogs
1. AlertDialog: Displays an alert message to the user with options like OK and
Cancel.
2. ProgressDialog: Displays a progress wheel or bar.
3. DatePickerDialog: Allows the user to select a date.
4. TimePickerDialog: Allows the user to select a time.
5. Custom Dialogs: Custom layouts designed by the developer.
AlertDialog Example:
java
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Alert")
.setMessage("This is an alert dialog.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
DatePickerDialog Example:
java
DatePickerDialog.OnDateSetListener dateSetListener = new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
String selectedDate = dayOfMonth + "/" + (month + 1) + "/" + year;
Toast.makeText(MainActivity.this, "Selected Date: " + selectedDate,
Toast.LENGTH_SHORT).show();
}
};
Lifecycle of a Dialog
java
@Override
protected Dialog onCreateDialog(int id) {
if (id == DIALOG_ID) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Alert")
.setMessage("This is an alert dialog.")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder.create();
}
return null;
}
@Override
protected void onPrepareDialog(int id, Dialog dialog) {
super.onPrepareDialog(id, dialog);
if (id == DIALOG_ID) {
// Update dialog before displaying it
}
}
@Override
protected void onShow(DialogInterface dialog) {
// Handle the dialog showing
}
@Override
protected void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
// Handle the dialog being dismissed
}
@Override
protected void onCancel(DialogInterface dialog) {
super.onCancel(dialog);
// Handle the dialog being canceled
}
Summary
+----------------------+
| onCreateDialog() |
+----------------------+
|
v
+----------------------+
| onPrepareDialog() |
+----------------------+
|
v
+----------------------+
| onShow() |
+----------------------+
|
v
+----------------------+
| onDismiss() |
+----------------------+
|
v
+----------------------+
| onCancel() |
+----------------------+