[go: up one dir, main page]

0% found this document useful (0 votes)
15 views37 pages

Android Exam Final

idk

Uploaded by

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

Android Exam Final

idk

Uploaded by

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

Introduction to Android

History of Mobile Software Development

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:

 1994: IBM Simon – the first smartphone.


 2007: Apple iPhone – revolutionized the smartphone industry with its
touchscreen and app ecosystem.
 2008: The first Android device, the HTC Dream, was released, introducing an
open-source platform that allowed developers to create a wide range of
applications.

The Open Handset Alliance

The Open Handset Alliance (OHA) is a consortium of technology companies, including


Google, HTC, Sony, Intel, and others. Formed in 2007, the OHA's goal is to accelerate
innovation in mobile technology by providing a more open and comprehensive platform
for mobile devices.

Key Points:

 Collaboration among 84 companies.


 Goals: Lower cost of developing and distributing mobile devices and applications.
 Flagship project: Android.

The Android Platform

Android is an open-source mobile operating system based on the Linux kernel. It


consists of several layers that provide a comprehensive environment for application
development.
Android Architecture:

 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:

 Android Studio: The official IDE for Android development.


 AVD Manager: Manages Android Virtual Devices (emulators).
 SDK Manager: Manages SDK packages.
 Build Tools: Utilities for building and packaging applications.

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

Creating your first Android application involves several steps:

1. Setting Up the Development Environment: Install Android Studio and


configure the SDK.
2. Creating a New Project: Use the new project wizard to set up the project
structure.
3. Writing Code: Implement the main activity and user interface.
4. Running the Application: Use an emulator or physical device to run the app.

Example:

 MainActivity.java:

java

package com.example.myfirstapp;

import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {


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

Anatomy of Android Application

An Android project includes several key files and directories:

 AndroidManifest.xml: Declares the app's components, permissions, and


metadata.
 res Directory: Contains resources like layouts, strings, images, and themes.
 src Directory: Contains the Java/Kotlin source files.
 assets Directory: Stores raw files like HTML, JSON, or other resources.
 gradle Scripts: Used for building and packaging the app.
Diagram:

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

 Context: Provides access to application-specific resources and classes.


o Example: Accessing resources, databases, and preferences.
 Activity: Represents a single screen with a user interface.
o Example: MainActivity.java.
 Services: Components that perform long-running operations in the background.
o Example: MyService.java.
 Intents: Messaging objects used to request an action from another app
component.
o Example: Starting a new activity.

Diagram:

Application Tasks with Activities

 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.

Activity Lifecycle States:

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;

public class MainActivity extends AppCompatActivity {

private static final String TAG = "MainActivity";

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

Managing Activity Transitions with Intents

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

Intent intent = new Intent(this, SecondActivity.class);


intent.putExtra("message", "Hello from MainActivity!");
startActivity(intent);

 SecondActivity.java:

java

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

Intent intent = getIntent();


String message = intent.getStringExtra("message");
TextView textView = findViewById(R.id.textView);
textView.setText(message);
}
Working with Services

Services in Android can be started (performing a single operation and stopping) or


bound (allowing components to bind to them to interact with). Key lifecycle methods
include onCreate(), onStartCommand(), onBind(), and onDestroy().

Example:

 MyService.java:

java

public class MyService extends Service {


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Perform background work here
return START_NOT_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
return null;
}

@Override
public void onDestroy() {
super.onDestroy();
// Clean up resources
}
}

Starting the service:

java
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
Receiving and Broadcasting Intents

Broadcast receivers allow applications to respond to broadcast messages from other


applications or the system. Applications can also broadcast their own messages.

Example:

 MyBroadcastReceiver.java:

java

public class MyBroadcastReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action != null && action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// Handle the broadcast message
Toast.makeText(context, "Boot completed", Toast.LENGTH_SHORT).show();
}
}
}

Registering the receiver in the manifest:

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

Sending a custom broadcast:

java
Intent intent = new Intent("com.example.CUSTOM_ACTION");
sendBroadcast(intent);

Registering a receiver for the custom broadcast: **CustomBroadcastReceiver.java


Using Android Manifest File

The AndroidManifest.xml file is a critical component of any Android application. It provides


essential information required by the Android system before it can run any of the
application's code.

Key Functions of the Manifest File:

 Declares the application's components (activities, services, broadcast receivers,


and content providers).
 Specifies permissions the application needs to access protected parts of the API
and interact with other apps.
 Declares the hardware and software features the app requires.
 Declares the application's package name, version information, and other
metadata.

Example:

xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapp">

<!-- Application metadata -->


<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<!-- Main activity -->


<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

<!-- Permissions -->


<uses-permission android:name="android.permission.INTERNET" />
</manifest>

Editing Manifest File Using Eclipse

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 Manifest File Manually

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

Managing an application's identity and system requirements involves declaring


necessary information in the manifest file, such as the package name, version codes,
and required hardware/software features.

Package Name and Versioning:

 Package Name: Uniquely identifies the application.


 Version Code and Version Name: Track versions of the application for updates.

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:

 Hardware Features: Specify hardware requirements such as camera, GPS, etc.


 Software Features: Specify software requirements such as OpenGL version.

Example:

xml
<uses-feature android:name="android.hardware.camera" android:required="true" />
<uses-feature android:name="android.hardware.location.gps" android:required="false" />

Registering Activity with Manifest File

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:

 INTERNET: Allows applications to open network sockets.


 ACCESS_FINE_LOCATION: Allows access to the device's precise location.

Example:

xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Managing Application Resources

Application resources are external files for strings, colors, dimensions, images,
animations, and menus. These resources are organized in the res directory.

Resource Types:

 Strings: Text used in the application.


 Colors: Color values used in the UI.
 Dimensions: Sizes and distances.
 Drawables: Graphics like bitmaps and shapes.
 Images: PNG, JPEG files.
 Animations: XML files defining animations.
 Menus: XML files defining application menus.

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>

Images: Store image files (PNG, JPEG) in the res/drawable directory.

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

Color resources define color values used in the application.

Example:

xml
<!-- res/values/colors.xml -->
<resources>
<color name="primary_color">#2196F3</color>
<color name="secondary_color">#FFEB3B</color>
</resources>

Dimension Resources

Dimension resources define sizes and distances used in the UI.

Example:

xml
<!-- res/values/dimens.xml -->
<resources>
<dimen name="padding_small">8dp</dimen>
<dimen name="padding_large">16dp</dimen>
</resources>
Drawable Resources

Drawable resources define graphics such as bitmaps and shapes.

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

Animation resources define animations using XML.

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

Menu resources define application menus.

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

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

Switch switch = findViewById(R.id.switch);


switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Handle switch 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

A ToggleButton is a two-state button that can be either checked or unchecked.

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

Date and Time Controls

Date and time controls allow users to select a date or time.

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.

Built-in Layout Classes

Android provides several built-in layout classes to arrange UI components in different


ways.

 FrameLayout: Stacks views on top of each other.

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>

 LinearLayout: Arranges views in a single column or row.

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

GridLayout places its children in a rectangular grid.

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

 TextView: Displays text.


 Spinner: Dropdown for selection.
 Buttons: Interactive elements.
 Checkboxes and Switches: Toggle options.
 RadioGroups: Grouped radio buttons.
 ToggleButton: Two-state button.
 Date and Time Controls: DatePicker and TimePicker.
 ProgressBar, SeekBar, RatingBar, Chronometer, Clocks: Various interactive
and display elements.
 ViewGroups: Container for other views.
 FrameLayout, LinearLayout, RelativeLayout, TableLayout, GridLayout:
Various ways to arrange UI elements.
 Multiple Layouts: Combining layouts to create complex interfaces.

Diagrams

TextView Example Diagram:

|-----------------------|
| Hello, World! |
|-----------------------|

Spinner Example Diagram:

|-----------------------|
| |---Dropdown---| |
| | Item 1 | |
| | Item 2 | |
| | Item 3 | |
|-----------------------|

Nested Layout Example Diagram:

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, GridView, GalleryView, ArrayAdapter, CursorAdapter

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 |
+---------+

GalleryView: GalleryView is a horizontal scrolling list of items. Note that GalleryView is


deprecated in newer versions of Android.

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 |
+---------+

ArrayAdapter: ArrayAdapter binds an array of data to views.

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

CursorAdapter: CursorAdapter binds data from a database cursor to views.

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, ListActivity, TabActivity

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

TabActivity: TabActivity manages multiple tabs. Note that TabActivity is deprecated in


newer versions of Android.

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:

 onAttach(): Called when the fragment is first attached to its context.


 onCreate(): Called to do initial creation of the fragment.
 onCreateView(): Called to create the view hierarchy for the fragment.
 onActivityCreated(): Called when the activity's onCreate() method has returned.
 onStart(): Called when the fragment is visible to the user.
 onResume(): Called when the fragment is visible and actively running.
 onPause(): Called when the fragment is partially obscured.
 onStop(): Called when the fragment is no longer visible.
 onDestroyView(): Called when the view hierarchy associated with the fragment
is being removed.
 onDestroy(): Called to do final cleanup.
 onDetach(): Called when the fragment is detached from its context.

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

A ListFragment is a fragment that displays a list of items. It simplifies the process of


displaying a list within a 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>

Working with Dialogs

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

Calendar calendar = Calendar.getInstance();


int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
DatePickerDialog datePickerDialog = new DatePickerDialog(this, dateSetListener, year, month, day);
datePickerDialog.show();

Lifecycle of a Dialog

The lifecycle of a dialog involves several stages from creation to dismissal.


Understanding this lifecycle helps in managing dialogs effectively in your application.

1. onCreateDialog(): Called to create the dialog.


2. onPrepareDialog(): Called before the dialog is shown to update its contents.
3. onShow(): Called when the dialog is shown.
4. onDismiss(): Called when the dialog is dismissed.
5. onCancel(): Called when the dialog is canceled.
Example:

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

 WebView Fragment: Embed a web browser within a fragment.


 Types of Dialogs: AlertDialog, ProgressDialog, DatePickerDialog,
TimePickerDialog, and custom dialogs.
 Lifecycle of a Dialog: Involves creation, preparation, showing, dismissal, and
cancellation stages.

Diagram: Dialog Lifecycle:

+----------------------+
| onCreateDialog() |
+----------------------+
|
v
+----------------------+
| onPrepareDialog() |
+----------------------+
|
v
+----------------------+
| onShow() |
+----------------------+
|
v
+----------------------+
| onDismiss() |
+----------------------+
|
v
+----------------------+
| onCancel() |
+----------------------+

You might also like