The development of mobile applications on the Android platform begins with an understanding of the screen architecture. Each interface that the user sees, be it the login page, the main product list, or profile settings, is technically a separate component. In the environment Android Studio this process is fine-tuned to the smallest detail, but requires strict adherence to the project structure. Beginners are often confused by the terms Activity and Fragment, but to create a full-fledged screen, you need to associate the logical part with the visual layout.
Adding a new screen is a fundamental task that every developer faces after creating a Hello World project. Errors at this stage can lead to problems with navigation or incorrect display of interface elements on different devices. It is important to immediately get used to the correct separation of logic and appearance using modern approaches. In this article, we'll look at creating a screen from scratch using the classic s View i XMLapproach, which remains the industry standard.
Before you start coding, you need to make sure that your project is open in Project (Android view) and not in file mode. This will make it easier to navigate through folders java and res. The whole process will take a few minutes if you follow the steps carefully. We will create a new Activity, describe its appearance and configure the transition to it.
Creating a new Activity through the wizard
The fastest and most reliable way to add a new screen is to use the built-in component creation wizard. This eliminates syntax errors when manually creating files and automatically registers the component in the application manifest. To begin, find the folder appin the left panel of the project, then go to java and select the package where your classes are stored (usually called com.example.myapp).
Right-click on the folder with the package, select New, and then Activity. You will see a window with a list of templates. For a simple screen, it is best to choose Empty Activity, since this template provides a blank canvas without unnecessary code. If you select a template with navigation or fragments, the wizard will add additional dependencies that can confuse a novice developer.
In the settings window that opens, specify the class name (for example, SecondActivity) and the file name. markup (for example activity_second.xml) Make sure that the checkbox Launcher Activity is unchecked if you do not want this to be the first screen of the application at launch. Also check the field Package name - it should correspond to the main package of your application.
โ๏ธ Creation check Activity
After clicking the button Finish IDE will generate two files: a Java/Kotlin logic class and an XML layout file. In the class you will see an overridden method onCreate, where the binding to the layout is already specified through the function setContentViewThis is a standard boilerplate design that Android Studio creates automatically for. each new screen.
Structure of XML screen layout
The appearance of any screen in Android is described in XML files located in the directory res/layout. This is where you determine where the buttons, text fields, and images will go. After creating an Activity through the wizard, the file activity_second.xml already contains the basic structure with a root element, most often it is ConstraintLayout or LinearLayout.
Open the created XML file. You'll see code similar to HTML, but with Android-specific attributes. The root element specifies the parameters of the container within which the widgets are located. For example, to add text to the screen, the tag TextViewis used, and for a button - Button. Each element must have unique width and height parameters, often set to wrap_content or match_parent.
It is important to correctly set identifiers (android:id) for all interactive elements. It is this ID that you will access elements from Java or Kotlin code to handle clicks or change text. Without a unique ID, it will be impossible to find an element in the tree, which will lead to compilation errors or logic failures.
Why is ConstraintLayout important?
ConstraintLayout allows you to create complex interfaces without nesting, which improves rendering performance. Unlike RelativeLayout, it uses a system of constraints to position elements relative to each other or screen boundaries.
Don't forget about the attribute tools:context on the root element. It does not affect the application's runtime, but it helps Android Studio understand which Activity this markup belongs to, which improves the preview and navigation in the code. This is a small thing, but it greatly simplifies development in large projects.
Setting up navigation between screens
Creating a screen is not enough - you need to provide the user with the ability to navigate to it. Navigation in Android is carried out through the object Intent. This is a special intermediary class that tells the system which component needs to be launched. To transition from one Activity to another, the so-called Explicit Intentis used, where the class of the target screen is explicitly indicated.
Suppose you have a main Activity with a button that, when clicked, should open a second screen. In the code of the first Activity, you need to find this button by ID and install an event listener on it. Inside the click processing method (onClick), a new Intent is created, the constructor of which is passed the context of the current Activity and the class of the target Activity.
button.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
This code creates an Intent instance and immediately launches the target Activity by the method startActivity. If you forget to pass in the correct context or class, the application may throw an error or launch the wrong screen. In complex applications, navigation can be complicated by data transfer, but the basic principle remains the same: Intent -> Start.
Use constants for Activity names to avoid refactoring mistakes. If you rename the Activity class, the hardcode of the name in the lines will lead to bugs, and the compiler will check the call through the class automatically.
There is also a concept Implicit Intentthat is used to launch components of other applications (for example, open a map or send an email), but for internal navigation of your application always use explicit Internets. This ensures that you control the user flow and know which screen will be opened.
Passing data between screens
Often, the new screen needs to display information received from the previous one. For example, when you click on a product in the list, a card for that particular product should open on the next screen. To transfer simple data (strings, numbers, Boolean values) between Activity, an object is used Bundle, which is nested in the Intent.
In the sending Activity, the data is packed into the Intent using the method putExtra. The key is the string from which the receiving party will retrieve the value. It is extremely important to use the same string keys in both places, otherwise the data will be lost. It is recommended to place the keys in a separate companion object or constant class.
intent.putExtra("USER_ID", 123)
intent.putExtra("IS_PREMIUM", true)
startActivity(intent)
In the receiving Activity (SecondActivity), the data is retrieved in the method onCreate. First you need to get the Intent with which the Activity was launched, and then call the corresponding getter methods (getIntExtra, getStringExtra etc.). If no data was passed, the methods will return default values, so always check for the presence of the key or use the default values.
To pass complex objects, such as data models, classes must implement an interface Parcelable (preferably for Android) or Serializable. This allows you to "pack" an object into a byte stream and pass it across the Activity process boundary. Parcelable is faster but requires more code to implement, while Serializable is easier to write but slower.
Registration in AndroidManifest.xml
Every Activity you create must be registered in a manifest file AndroidManifest.xml. This file is an application passport for the Android operating system. If you created an Activity through the wizard (as described in the first section), the entry will appear automatically. However, if you manually create classes or delete entries by mistake, the application will not start, throwing an exception ActivityNotFoundException.
Open the manifest file in the folder manifests. Inside the tag there should be a tag with an attribute indicating the full path to your class. For the main Activity, an intent-filter is also added with action application there must be a tag activity with attribute android:name, pointing to the full path to your class. For the main Activity, an intent-filter with action is also added MAIN and category LAUNCHER, which makes it the entry point into the application.
Attribute
Value
Description
android:name
.SecondActivity
Name of the Activity class (the dot at the beginning indicates the application package)
android:label
@string/app_name
Screen title displayed in the task manager
android:theme
@style/Theme.App
Theme (colors, fonts) for this screen
android:parentActivity
.MainActivity
Indicates the logical parent for the "Top" navigation
The attribute android:theme allows you to set a unique design for a specific screen, different from the global theme of the application. This is useful if, for example, the settings screen should be dark and the rest of the application light, or to implement full-screen modes without an actionBar.
โ ๏ธ Attention: When changing the package name in the Gradle settings or when renaming project folders, the paths in AndroidManifest.xml may no longer correspond to reality. Always make sure that the path in the name attribute matches the actual location of the class in the package structure.
Common errors and debugging
When adding new screens, developers often encounter a number of common problems. One of the most common is NullPointerException when trying to find a view by ID. This occurs if the ID in the XML file does not match the one used in the code, or if setContentView is called after an attempt to find the element. Always check the order of the lines in the method onCreate.
Another common mistake is (forgetting to) register the Activity in the manifest. In this case, when you try to switch, the application will simply crash, and in the logs (Logcat) you will see a message that the Activity was not found. Read the stack trace of the error carefully; it usually directly points to the missing component.
Problems may also arise with the theme. If you use Material Design components (for example MaterialButton), but your theme does not define theme.material or the required color attributes, your application may throw an XML bloat error (InflateException). Make sure that your application inherits from the correct base theme, for example Theme.MaterialComponents.DayNight.
The main source of errors when creating screens is desynchronization between XML markup and Java/Kotlin code. Always check that IDs and data types match when passing arguments.
For debugging, use the tool Logcat in Android Studio. It displays all system messages and application errors in real time. Filter the logs by your application tag so as not to drown in system noise, and pay attention to the red lines with the text "FATAL" or "CRASH".
Frequently asked questions (FAQ)
Is it possible to create a screen without an XML file?
Yes, it is possible. You can create the entire layout programmatically using the View and LayoutParams classes in Java or Kotlin code, and pass the created root View to the setContentViewmethod. There is also a toolkit Jetpack Composethat allows you to write an interface entirely in Kotlin without using XML, which is becoming a new standard in modern Android development.
What is the difference between an Activity and a Fragment?
Activity is a separate application screen that has its own living window and is independent from others. Fragment (fragment) is a modular part of the interface that lives inside an Activity. Fragments allow you to create flexible interfaces that adapt to tablets (several fragments on one screen) and smartphones (one fragment per screen).
How to transfer a complex object (for example, a list of products) to a new screen?
To transfer lists or complex objects, the class must implement the interface Parcelable (recommended) or Serializable. After this, the object can be placed in the Intent using the putExtramethod. For very large amounts of data, it is better to use architecture patterns (MVVM/MVP) and data stores (Repository), passing only an ID or a link, and loading the data in a new screen independently.
Why doesn't Android Studio see my new Activity class?
Make sure the class is in the correct package (folder) specified in AndroidManifest.xml. If you moved files manually, the paths might get confused. Also check for compilation errors in the Activity file itself, as the IDE may not offer a class for selection if it has syntax errors.