Activities and Fragments are fundamental building blocks of Android application development. They are used to create screens, manage user interactions, and organize application functionality. Understanding how Activities and Fragments work is essential for building modern, scalable, and user-friendly Android applications.
Most Android applications use a combination of Activities and Fragments to provide smooth navigation and efficient screen management.
What is an Activity?
An Activity represents a single screen in an Android application. It acts as the entry point for user interaction and provides a window where UI components such as buttons, text fields, images, and lists can be displayed.
Examples of Activities include:
- Login Screen
- Registration Screen
- Home Screen
- Profile Screen
- Settings Screen
- Product Details Screen
Each screen that users interact with is usually implemented as an Activity.
Why are Activities Important?
Activities are important because they:
- Display user interfaces
- Handle user interactions
- Manage application screens
- Support navigation
- Control application workflow
- Connect UI with business logic
Every Android application contains at least one Activity.
Creating an Activity
Android Studio automatically creates a MainActivity when a new project is generated.
Example:
public class MainActivity
extends AppCompatActivity {
@Override
protected void onCreate(
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(
R.layout.activity_main);
}
}
This Activity loads the layout file when the application starts.
Activity Lifecycle
The Activity Lifecycle defines the different states an Activity goes through during its existence.
Important lifecycle methods include:
onCreate()
Called when the Activity is first created.
@Override
protected void onCreate(
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
onStart()
Called when the Activity becomes visible.
onResume()
Called when the Activity becomes active and ready for user interaction.
onPause()
Called when the Activity is partially hidden.
onStop()
Called when the Activity is no longer visible.
onDestroy()
Called before the Activity is removed from memory.
Understanding the lifecycle helps developers manage resources efficiently.
Navigating Between Activities
Activities can communicate using Intents.
Example:
Intent intent =
new Intent(
MainActivity.this,
SecondActivity.class);
startActivity(intent);
This opens another Activity.
What is a Fragment?
A Fragment is a reusable portion of a user interface that exists within an Activity.
Fragments allow developers to divide a screen into smaller, manageable sections.
Unlike Activities, Fragments cannot exist independently and must be hosted inside an Activity.
Examples of Fragment usage:
- Navigation panels
- Dashboard sections
- Product lists
- Chat windows
- Profile tabs
Fragments improve flexibility and reusability.
Why Use Fragments?
Fragments provide several advantages:
- Reusable UI components
- Better screen organization
- Easier maintenance
- Improved performance
- Tablet and phone support
- Flexible layouts
Modern Android applications commonly use Fragments instead of multiple Activities.
Activity vs Fragment
| Feature | Activity | Fragment |
|---|---|---|
| Represents a screen | Yes | No |
| Can exist independently | Yes | No |
| Requires hosting component | No | Yes |
| Reusable | Limited | Highly reusable |
| Lifecycle | Full lifecycle | Dependent lifecycle |
| Navigation unit | Yes | Usually inside Activity |
Activities and Fragments often work together.
Creating a Fragment
Create a new Fragment class.
Example:
public class HomeFragment
extends Fragment {
}
The Fragment class represents a reusable UI component.
Fragment Layout
Each Fragment typically has its own XML layout file.
Example:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Home Fragment" />
This layout defines the Fragment’s user interface.
Fragment Lifecycle
Fragments have their own lifecycle methods.
Important methods include:
onAttach()
Called when the Fragment attaches to an Activity.
onCreate()
Initializes Fragment resources.
onCreateView()
Creates the Fragment UI.
Example:
@Override
public View onCreateView(
LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(
R.layout.fragment_home,
container,
false);
}
onDestroyView()
Called when the Fragment UI is removed.
onDetach()
Called when the Fragment disconnects from its Activity.
Understanding the Fragment lifecycle is essential for proper resource management.
Adding a Fragment Dynamically
Example:
FragmentManager fragmentManager =
getSupportFragmentManager();
FragmentTransaction transaction =
fragmentManager.beginTransaction();
transaction.replace(
R.id.fragmentContainer,
new HomeFragment());
transaction.commit();
This loads a Fragment into a container.
Fragment Container
The Activity layout requires a container for displaying Fragments.
Example:
<FrameLayout
android:id="@+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Fragments are displayed inside this container.
Passing Data to a Fragment
Example:
Bundle bundle = new Bundle();
bundle.putString(
"username",
"Ali");
HomeFragment fragment =
new HomeFragment();
fragment.setArguments(bundle);
Receiving data:
String username =
getArguments()
.getString(
"username");
This enables communication between Activities and Fragments.
Fragment Communication
Fragments often communicate with their host Activity.
Example:
public interface OnItemSelected {
void onSelected(String item);
}
The Activity implements the interface and receives updates from the Fragment.
This approach keeps components loosely coupled.
Multiple Fragments
A single Activity can contain multiple Fragments.
Example:
MainActivity
โ
โโโ MenuFragment
โ
โโโ ContentFragment
This design is common in tablet applications and dashboards.
Benefits of Fragments
Fragments provide several advantages:
Reusability
The same Fragment can be used in multiple Activities.
Better Organization
Large screens can be divided into smaller components.
Flexible UI Design
Different layouts can be created for phones and tablets.
Easier Maintenance
Individual Fragments can be updated without modifying entire Activities.
These benefits make Fragments an important part of modern Android architecture.
Real-World Applications
Activities and Fragments are used in:
- Social media applications
- Banking systems
- E-commerce platforms
- Learning management systems
- Healthcare applications
- News applications
- Streaming services
- Enterprise software
Most modern Android apps use Fragments extensively.
Common Beginner Mistakes
Forgetting Fragment Containers
Fragments require a container inside the Activity layout.
Using Too Many Activities
Modern Android development often prefers Fragments for screen management.
Ignoring Lifecycle Methods
Improper lifecycle handling can cause memory leaks and crashes.
Direct Fragment Dependencies
Use interfaces or ViewModels instead of tightly coupling Fragments.
Best Practices
When working with Activities and Fragments:
- Keep Activities lightweight
- Use Fragments for reusable UI
- Understand lifecycle methods
- Avoid unnecessary Fragment nesting
- Use ViewBinding where possible
- Follow Android architecture guidelines
These practices improve maintainability and performance.
Importance of Activities and Fragments
Activities and Fragments are important because they:
- Form the foundation of Android UI development
- Support application navigation
- Improve code organization
- Enable reusable interfaces
- Enhance scalability
- Create responsive user experiences
Every Android developer must understand how they work together.
Conclusion
Activities and Fragments are core components of Android application development. Activities represent complete screens, while Fragments provide reusable and flexible UI sections that operate within Activities. By understanding lifecycle management, navigation, communication, and dynamic UI design, developers can build modern Android applications that are scalable, maintainable, and user-friendly. Mastering Activities and Fragments is an essential step toward becoming a professional Android developer.