In modern Android development, the activity state and fragment lifecycle play a crucial role, influencing implementation decisions as well as the final output that is viewed and experienced by end users. In this article, we’ll review what these concepts are, how they work, and what steps to follow to implement them in an Android application.
To follow along with this tutorial, you’ll need basic knowledge of the Kotlin programming language as well as Android Studio or IntelliJ IDE installed. Let’s get started!
FragmentManager
and fragment lifecycle stateAn activity refers to a single action that a user can perform. In Android development, an activity is a Java class that has some pre-defined functions that can be triggered in different app states to perform any kind of task you want. The activity is also responsible for the creation, destruction, and control of the other states of the app’s lifecycle.
An activity class handles many of the computation details, like creating a window for you.
In Android, there can be multiple activities, but there is only one MainActivity
, which is the entrance of the application, just like the main()
method begins the execution of a program in Java. When we call the MainActivity
class, the execution begins with the onCreate()
method.
The subclass of all activities implement two methods:
onPause
: Enables the user to pause active interaction with the activityonCreate
: Initializes your activities. You’ll have to call the setContentView()
programmaticallyWe can express this in the code snippet below. We use the onCreate
method to create or start an activity, the super
keyword to call the super class constructor, and finally, setContentView
to set the XML:
package com.example.myfirstandroidapplication import android.os.Bundle import com.google.android.material.snackbar.Snackbar import androidx.appcompat.app.AppCompatActivity import androidx.core.view.WindowCompat import androidx.navigation.findNavController import androidx.navigation.ui.AppBarConfiguration import androidx.navigation.ui.navigateUp import androidx.navigation.ui.setupActionBarWithNavController import android.view.Menu import android.view.MenuItem import com.example.myfirstandroidapplication.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private lateinit var appBarConfiguration: AppBarConfiguration private lateinit var binding: ActivityMainBinding override fun onCreate(savedInstanceState: Bundle?) { WindowCompat.setDecorFitsSystemWindows(window, false) super.onCreate(savedInstanceState) binding = ActivityMainBinding.inflate(layoutInflater) setContentView(binding.root) setSupportActionBar(binding.toolbar) val navController = findNavController(R.id.nav_host_fragment_content_main) appBarConfiguration = AppBarConfiguration(navController.graph) setupActionBarWithNavController(navController, appBarConfiguration) binding.fab.setOnClickListener { view -> Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) .setAnchorView(R.id.fab) .setAction("Action", null).show() } } override fun onCreateOptionsMenu(menu: Menu): Boolean { // Inflate the menu; this adds items to the action bar if it is present. menuInflater.inflate(R.menu.menu_main, menu) return true }
An activity state refers to events that are triggered by either the system or by users, resulting in the transition of an activity from one state to another.
For example, when a user is active in an app, they usually transition between clicking the app’s icon on their homepage, to launching the app, then ultimately exiting from the app, resulting in state changes. These changes from one state to another are what is known as an activity state change.
The activity changes that occur in a system are managed in activity stacks. The latest activity is usually placed on top of the current stack, and it becomes the running activity while the previous activity remains below it in the stack.
The activity lifecycle refers to the entire activity that a user performs, from launching the app to shutting down all operations. Several activity methods define the entire lifecycle of an activity. For one, onCreate()
is the initial state of the app after being launched by the user. The code snippet below shows the syntax for the onCreate()
method:
protected void onCreate()
onPause()
is a paused state when the user is about to decide the next line of action, whether to exit or continue using the app:
protected void onPause()
The onStart()
state is called when the activity resumes from the paused state and is made visible to the user:
protected void onStart()
onDestroy()
is a state that results when all activities are closed down, resulting in shutting down all operations:
protected void onDestroy()
onStop()
is the state that results from the user clicking on the home button, which usually minimizes the app. This should not be mistaken for when the app is closed:
protected void onStop()
onResume()
is a callback that is invoked when an activity restarts after being stopped. The syntax for this method is shown in the code snippet below:
protected void onResume()
The methods listed above work in combination with the saveInstanceState()
method to preserve the configuration of the activity UI state:
public class Activity extends ApplicationContext { protected void onCreate(Bundle savedInstanceState); protected void onStart(); protected void onRestart(); protected void onResume(); protected void onPause(); protected void onStop(); protected void onDestroy(); }
A fragment refers to the portion of an activity’s UI that allows us to create multiple screens in our Android application. Fragments were introduced in Android v3.0 to support a more flexible UI design on large screens like tablets. The latest version of Android at the time of writing, v12.x, includes extra features like a more expressive and dynamic system UI.
One approach we can follow to create multiple screens in an application is swapping one fragment with another.
Activities are generally regarded as the operating system’s entry point to the application. In an Android application, the activity can contain more than one fragment and functions. These serve as a frame that contains the UI fragment, providing UI elements that surround the fragment.
While an activity can exist without a fragment, you cannot use a fragment without an activity. The UI fragments operate like a view within the activity’s layout. To achieve this, you have to create a sub-class, like in the code below:
class InfoFragment: Fragment{ @override fun onCreateView(...): View? { return inflater.inflate ( R.layout.fragment_info,...) } }
The code snippet above shows a reusable UI component containing UI logic that inflates the layout of the fragment. While most UI elements are implemented in the fragment, the OS can only open activities.
Note that within the activity, you can tell Android which layout to use by calling setContentView
in onCreate
. While in the fragment, you’ll have to manually inflate and return the inflated layout within the onCreateView
method, which is independent of the onCreate
method.
The code snippets below further emphasize that point:
// Activity override fun onCreate(savedInstanceState : Bundle?) { super.onCreate(savedInstanceState) val binding = DataBindingUtil .setContentView<ActivityMainBinding> ( this, R.layout.activity_main) ... }
// Fragment override fun onCreateView (...): View? { return inflater.inflate ( R.layout.fragment_message,...) }
While activities inherit from the context
class, fragments do not. You’ll need to use the context
property within a fragment to have access to app data that is accessible to the context
, like strings or images.
// Activity public class ActivityCompat extends ContextCompat
//Fragment open class Fragment: componentCallbacks
context!!.getString(R.string.app_name)
context!!.getDrawable(R.drawable.ic_launcher_background
In Android, you can navigate to and from between different activities. They are arranged in a stack with the latest activity on top of the stack trace, called the back stack
.
Fragments have a similar back stack
, but the entire stack is contained within the activity. This is controlled by a class known as FragmentManager
, which we’ll review next.
FragmentManager
and fragment lifecycle stateIn Android application development, the FragmentManager
and fragment lifecycle are responsible for the state transition that the application undergoes.
A fragment always begins by being instantiated in an INITIALIZED
state. For this fragment to transition throughout the different states in its lifecycle, it must be added to FragmentManager
. The FragmentManager
determines what state its fragment should be in and determines the fragment’s maximum state.
Just like an activity, fragments also have their own lifecycle. Whenever a user interacts with an Android application, the fragment transitions through different states in its lifecycle, including the following:
INITIALIZED
CREATED
STARTED
RESUMED
DESTROYED
However, the best way to learn about fragments is by implementing them.
To create a fragment, we’ll follow the steps below:
TitleFragment
for the fragment’s nameAfter creating a fragment, you’ll have to add the fragment to your application. To add a fragment, first click on the linear
layout and create a fragment tag from the activity_main.xml
layout. Give this fragment a fragment id
and an android:name
to the full path of the fragment class. Finally, set the layout width and height to match_parent
, and you’re good to go!
In this tutorial, we covered some basic and advanced concepts on activity state and fragment lifecycle in an Android application using the Kotlin programming language.
Fragments support modularity and code reuse, allowing us to use the same list view in many activities. They’re also helpful for building multi-pane interfaces for Android tablet devices. On the other hand, the activity state lifecycle provides information on how the Android application would behave throughout its seven states. Finally, we created some fragment lifecycle examples, comparing their similarities and differences between activity state.
As an Android developer, it’s important to always stay up to date with latest technology release and follow best practices during Android application developments. I hope you enjoyed this article, and leave a comment if you have any questions. Happy coding!
LogRocket is an Android monitoring solution that helps you reproduce issues instantly, prioritize bugs, and understand performance in your Android apps.
LogRocket also helps you increase conversion rates and product usage by showing you exactly how users are interacting with your app. LogRocket's product analytics features surface the reasons why users don't complete a particular flow or don't adopt a new feature.
Start proactively monitoring your Android apps — try LogRocket for free.
Hey there, want to help make our blog better?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowCompare Prisma and Drizzle ORMs to learn their differences, strengths, and weaknesses for data access and migrations.
It’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.
Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.