Difference between Activity and Fragment
In Android development, both Activities and Fragments are used to create the user interface (UI) of an app, but they serve different purposes and have distinct characteristics.
Activity:
An activity is a single, focused screen that users can interact with. It represents an application’s primary UI and acts as an entry point for user interactions. Activities are integral components of an Android app, and every app must have at least one activity.
Activities are independent entities that are typically full-screen and manage the entire lifecycle of a screen, from creation to destruction. They are responsible for hosting UI elements like buttons, text fields, images, etc.
Only one activity can be in the foreground (active) at any time, and it can start other activities using intents.
Fragment:
A fragment is a reusable portion of the UI that can be embedded within an activity. It is like a sub-activity, but unlike an activity, it cannot exist independently and must be hosted within an activity.
Fragments are often used to create dynamic and flexible UIs that can adapt to different screen sizes, such as tablets and smartphones. For example, an app can display two fragments side by side on a tablet but only one fragment at a time on a smartphone.
A fragment has its own lifecycle, similar to an activity, but it is closely tied to the lifecycle of its host activity. This allows for more modular and reusable UI components Activity and Fragment.
Table of Contents
Key Differences:
Independence: An activity is a standalone component, while a fragment must be hosted within an activity.
Lifecycle: Although both have lifecycles, a fragment’s lifecycle is tied to the lifecycle of its host activity.
UI Scope: An activity usually occupies the entire screen, while fragments are typically used to represent a portion of the UI within an activity.
Reusability: Fragments are more reusable and can be added, replaced, or removed dynamically within activities, making them suitable for multi-pane layouts.
Java Example: Using Activity and Fragment
Activity Example (MainActivity.java):
```java
package com.example.myapp;
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);
// Check if the fragment container exists
if (findViewById(R.id.fragment_container) != null) {
// If we're being restored from a previous state, don't do anything
if (savedInstanceState != null) {
return;
}
// Create a new fragment
MyFragment firstFragment = new MyFragment();
// Add the fragment to the 'fragment_container' FrameLayout
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment_container, firstFragment).commit();
}
}
}
```
Fragment Example (MyFragment.java):
```java
package com.example.myapp;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
public class MyFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_layout, container, false);
}
}
```
XML Layout for Activity (activity_main.xml):
```xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
```
XML Layout for Fragment (fragment_layout.xml):
```xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello from Fragment!" />
</LinearLayout>
```
Explanation of the Code:
- MainActivity.java: This activity hosts a fragment. It uses a
FrameLayout
as a container for the fragment. The fragment is added dynamically at runtime. - MyFragment.java: This fragment represents a part of the UI. It inflates a simple layout with a
TextView
. - activity_main.xml: This layout defines a container (
FrameLayout
) where the fragment will be placed. - fragment_layout.xml: This layout defines the UI for the fragment, which consists of a
TextView
.
This example demonstrates how an activity can host a Activity and Fragment, showcasing the modularity and reusability of fragments.