Development of mobile applications on platform Android starts with understanding the basic components, and the most important of them is the Activity. It is this that represents a separate screen with a user interface that a person sees when interacting with your software product. Without competent creation and configuration of this element, it is impossible to imagine the operation of any modern application, be it a simple calculator or a complex social network.
The process of creating a new activity in the environment Android Studio may seem confusing for a beginner due to the many generated files and settings. However, if you understand the logic of the work IDE and the structure of the project, this procedure becomes routine and quick. In this guide, we'll go through every step in detail, from choosing a template to running the finished screen on an emulator or real device.
Understanding how the system manages the activity lifecycle is a critical skill for any developer. Errors at this stage often lead to memory leaks or incorrect display of the interface when the screen is rotated. We will focus not only on the technical side of creating the file, but also on the correct binding of Java or Kotlin code with XML markup.
Android architecture fundamentals and the role of ActivityAndroid application architecture is based on the concept of components that interact with each other as needed. Activity is one of the four main components along with services broadcast receivers and content providers. Each activity is responsible for a specific interaction screen, providing a window in which the application draws its user interface.
When you run an application, Android creates an instance of the Activity class and calls its onCreate method. It is at this moment that primary initialization, loading of resources and construction of the visual part of the screen occur. It is important to understand that activity does not exist in a vacuum; it is closely linked to the manifest file AndroidManifest.xmlwhere all public components of the application are declared.
Always make sure that your activity is declared in the manifest, otherwise the system simply will not be able to launch it, even if the code is written perfectly.
The life cycle of an activity includes several states: running, suspended, stopped and destroyed. The transition between these states is controlled by the system depending on user actions. For example, if the user opens another application, your activity goes into a stopped state, freeing up CPU resources for the current task.
Creating an Activity through the Android Studio WizardThe most reliable and fastest way to add a new screen to a project is to use the built-in Component Creation Wizard. To do this, right-click on the folder java or kotlin in the project structure, select item New, and then Activity. The menu that opens will offer several templates, each of which is suitable for certain use cases.
Among the available options, the most commonly used are Empty Activity and Empty Views Activity. The first template creates the smallest possible activity without unnecessary elements, which is ideal for complete control over the code. The second option includes a basic structure with TextView, which can be convenient for quick tests or simple welcome screens.
After selecting a template, the wizard will prompt you to configure the generation parameters. This specifies the name of the activity class, the name of the layout file, and the name of the parent class. It is generally recommended to leave the default values โโunless you are creating a specific architecture using FragmentActivity or AppCompatActivity.
Structure of created files and their purposeAfter completing the wizard, several new files appear in the project, each of which plays its own role. The main file is the activity class (for example, SecondActivity.kt or .java), which contains the logic of the screen. This file handles button clicks, loading data, and lifecycle management.
At the same time, an XML markup file is created or selected, usually located in the folder res/layout. This file is solely responsible for the visual display of elements: buttons, text fields, images. Separating logic and appearance is a fundamental principle of Android development, known as separation of concerns.
Why do you need two different files?
Separation of logic code (Kotlin/Java) and markup (XML) allows you to change the application design without affecting the app code, and vice versa.
The third important element is entry in the manifest file. When creating an activity through the wizard, Android Studio automatically adds the appropriate tag <activity> to AndroidManifest.xml. If you create files manually, you will have to perform this step yourself, otherwise the component will remain invisible to the system.
Configuring AndroidManifest.xml and launching the activityThe file AndroidManifest.xml is the passport of your application, where its structure is described. For each activity there must be a corresponding entry indicating to the system the existence of that component. The basic declaration looks simple, but can contain additional attributes to control the behavior of the screen.
Inside the tag <activity> you can specify a theme, screen orientation, and other parameters. For example, to make an activity full screen or hide the status bar, special theme attributes are used. It also determines whether the activity is the main entry point into the application through the filter.intent.
โ ๏ธ Attention: If you forget to add an activity to the manifest, when you try to launch it through Intent, the application will crash with an error ActivityNotFoundException.
To launch the created activity from another part of the application, the mechanism Intentsis used. These are message objects that pass requests to the Android component to perform an action. An explicit intent specifies a specific class of activity to run, which is standard for navigation within a single application.
The relationship between code and XML markupAfter creating the files, you need to ensure that the activity loads the correct XML markup. The method onCreate calls a function setContentView, which is passed the layout resource identifier. Without this call, an empty white field will be displayed on the screen, since the system does not know what exactly to draw.
To interact with interface elements, such as buttons or input fields, the findViewById method or view binding mechanism is used. The first approach is classic, but requires a type cast and may be less secure. View binding is a more modern alternative that generates classes for secure access to widgets.
โ๏ธ Checking the connection between Activity and Layout
It is important to monitor the correspondence of identifiers (android:id) in the XML file and in the Java/Kotlin code. If you try to find an element by an incorrect ID, the application will crash with an exception NullPointerException or similar error. Always check the namespace and spelling of identifiers.
Main Lifecycle Methods TableUnderstanding when and which method is called helps you manage resources efficiently. Below is a table describing the key methods you'll see in the activity class.
| Method | Description | When called |
|---|---|---|
onCreate |
Activity initialization | When an instance is first created |
onStart |
The activity becomes visible | When the activity appears on the screen |
onResume |
Activity in focus | When the user can interact with the screen |
onPause |
Pause of activity | When another activity overlaps the current one |
Each of these methods is an extension point where the developer can add his own logic. For example, in onPause they often save unsaved data, and in onResume update information from the network. Ignoring these methods can lead to a poor user experience.
Typical errors and how to fix themOne โโof the most common problems is LeakCanary or a memory leak when an activity does not release resources after being destroyed. This often happens if the activity has background threads or asynchronous tasks running that continue to run after the screen is closed. Always make sure that all subscriptions and threads are stopped in the method onDestroy.
Another common mistake is trying to update the UI from a background thread. Android strictly prohibits changing interface elements from outside the main thread (UI Thread). To solve this problem, use mechanisms runOnUiThread, Handlers or modern coroutines (Coroutines) in Kotlin.
Never perform long-running operations, such as database or network queries, in the main activity thread - this will lead to an interface (ANR).
It is also worth mentioning the problem of re-creating the activity when turning screen. By default, when the device orientation changes, the activity is destroyed and recreated, which may result in the loss of user input. To save state, use savedInstanceState or ViewModel.
โ ๏ธ Attention: Android Studio interfaces and support libraries are constantly updated. Some methods may be marked as deprecated. Always check Google's official documentation for the latest implementation guidelines.
Using modern approaches: Jetpack and NavigationModern development is shifting from directly creating multiple activities to using a single activity and multiple Fragment. This approach simplifies navigation, allows for a single toolbar, and improves application performance. The library Android Jetpack Navigation makes it much easier to manage transitions between screens.
Instead of creating a new activity for each screen, developers create fragments that are embedded in the main activity container. This allows you to implement complex scenarios, such as a responsive interface for tablets, where two fragments can be displayed side by side.
What is the advantage of a single Activity?
Using a single activity simplifies application state management, speeds up transitions and makes navigation more predictable and smooth.
Moving to a single activity architecture requires a change in thinking, but in the long run it pays off in code stability. Libraries ViewModel and LiveData or StateFlow help to separate display logic and business logic, making the code testable and clean.
Frequently asked questions (FAQ)
Is it possible to create activity without an XML file?
Yes, technically you can create the entire interface programmatically using classes LinearLayout, TextView and others, and pass them to setContentView. However, this approach is considered outdated and difficult to support for large projects.
Why does Android Studio suggest choosing Parent Activity?
Selecting a parent activity is needed to automatically configure the "Back" button in the top panel (Action Bar) and create the correct navigation chain. This improves by allowing the user to easily return to the previous screen.
What is the difference between an Activity and a Fragment?
An Activity is a separate application screen managed by the system. Fragment is a modular part of the interface that lives inside an Activity. Fragments are more flexible: they can be added, removed and replaced dynamically without reloading the entire activity.
How to transfer data from one activity to another?
Objects are used to transfer data Intent. They can contain primitive data types, strings, or serializable objects through methods putExtra. For complex objects, it is better to use Parcelable or Serializable.