Developing applications for mobile devices begins with understanding the basic components, and the first step is always creating an Activity. It is this element that represents a separate screen with a user interface that a person sees when interacting with your product. In the environment Android Studio the process of creating new screens is automated, but requires careful attention to detail to avoid compilation errors or navigation problems.
Beginners often confuse the concepts of Activity and Fragment, but the difference is fundamental: an Activity is a container, and a Fragment is part of the content inside it. When you run a project, Android reads the configuration file and determines which component should run first. Correct code structure and compliance with the Naming Convention at this stage will save you hours of debugging in the future.
In this article we will analyze the entire process from creating a new class to displaying a picture on the smartphone screen. You will learn how to associate XML markup with application logic and understand how the component life cycle works. Readiness working in an integrated development environment is the only thing you need to get started.
Project preparation and file structure
Before adding new ones screens, you need to make sure that your project is created correctly. At start Android Studio prompts you to select a template, and for most cases, the optimal choice will be "Empty Activity". This template creates the minimum required file structure, including the application entry point. If you are using older versions of the IDE, the interface may be different, but the logic remains the same.
All application resources, such as images, strings, and interface layouts, are stored in the folder res. This is where the XML files that describe the appearance of your screen are located. The logic of the work is written in the folder java (or kotlinif you chose this language), where the classes that inherit from the base Activity class are located. Separation of resources and code is a key principle of the Android architecture.
โ ๏ธ Attention: When creating a new project, pay attention to the "Package name" field. Changing it after creating a project is extremely difficult; it is often easier to create the project again than to try to rename packages manually.
The structure of a modern project can be confusing for a beginner due to the large number of Gradle configuration files. However, to create a simple screen, you only need to know two basic file types: a programming language class and a markup file. The remaining files are responsible for the assembly, dependencies and manifest, which we will talk about later.
Creating a new Activity through the wizard
The most reliable way to add a new screen is to use the built-in creation wizard. To do this, right-click on the folder with your code (usually app > java > com.example.app), select New, and then Activity. In the menu that opens, select "Empty Activity" to get a blank sheet without unnecessary code, or "Basic Activity" if you need a template with a menu and a floating button.
The wizard will offer to fill in several fields that are critical for further work. The "Activity Name" field specifies the name of the class, for example SecondActivity. The "Layout Name" field specifies the name of the XML file, for example activity_second. Automatic generation of names helps keep things organized, but you can rename them if you follow your naming system.
- ๐ฑ Activity Name โthe name of the Java or Kotlin class where the logic is written.
- ๐จ Layout Name โthe name of the XML file that describes the appearance.
- ๐ท๏ธ Launcher Activity โthe check mark that makes this the starting screen at startup applications.
- ๐ Source Language โchoose between Kotlin and Java for the generated code.
After clicking the "Finish" button, the development environment will create two files and automatically make the necessary changes to the application manifest. This eliminates the need for manually specifying paths and reduces the risk of syntax errors. If you choose to create the files manually, you will have to register each component yourself in the system configuration file.
Use naming prefixes, such as LoginActivity, SettingsActivity, MainActivity. This will make navigating the project much more convenient when there are more than ten files.
Manual creation and registration in Manifest
Sometimes automatic creation is not suitable, for example, when copying code from old projects or using specific templates. In this case, you create the class manually, inheriting from AppCompatActivity. However, the system will not know anything about the existence of the new screen until you register it. Registration occurs in a file AndroidManifest.xml, which is located in the folder manifests.
Inside the tag you need to add a new tag . The attribute android:name indicates the class, and the attribute android:label sets the title that will be visible in the status bar or in the history of running applications. Without this entry, an attempt to launch an Activity through an Intent will cause the application to crash with an error ActivityNotFoundException.
<activity android:name=".SecondActivity"android:label="@string/title_activity_second"
android:parentActivityName=".MainActivity" />
Particular attention should be paid to the attribute parentActivityName. It is needed for the "Back" button in the upper corner of the screen to work correctly. If you don't specify a parent, the navigation may behave unpredictably, taking the user back to a place other than expected. This is especially important in applications with deeply nested screens.
โ ๏ธ Attention: Each Activity, even temporary or service, must be declared in the manifest. The only exceptions are activities implemented in other applications through libraries, but within one project the rule is strict.
What happens if you forget to register an Activity?
The application crashes instantly when you try to navigate. In the logs (Logcat) you will see the error android.content.ActivityNotFoundException with the message "Unable to find explicit activity class".
Working with XML interface markup
The appearance of the screen is described in the XML file that the wizard created along with the class. By default there is a simple text view with a greeting. To change the contents, open the file activity_main.xml (or whatever you named it). In Android Studio there are two viewing modes: Code (XML code only) and Split (code and visual representation at the same time).
The main markup element is often ConstraintLayout, which allows you to position elements relative to each other or the edges of the screen. This makes the interface responsive to different display sizes. You can drag buttons and text fields from the Palette directly onto the canvas, and the IDE itself will generate the necessary XML code.
| XML element | Description | Analog in code |
|---|---|---|
TextView |
Text label, header | TextView |
Button |
Button to press | Button |
EditText |
Text input field | EditText |
ImageView |
Image container | ImageView |
Each interface element that you plan to interact with in code must be assigned a unique identifier via an attribute android:id. For example, android:id="@+id/myButton". Without this ID, you will not be able to find the element in the Activity code and assign an event handler to it. Identifiers must be unique within one XML file.
โ๏ธ Checking XML markup
Linking code and interface
After the interface is created, we need to โreviveโ it. In the Activity class, usually in a method onCreate, initialization occurs. Here you use the setContentViewmethod to tell the system which XML file to load. In Kotlin this is often done through the syntactic sugar view binding or simply findViewById, in Java - through an explicit method call.
To access elements, a method is used findViewById, which takes the resource ID and returns an object of the corresponding type. For example, to find a button, you need to cast the result to the Button type. In modern versions of Android Studio and when using View Binding, this process becomes safer and more readable, eliminating the need for constant type casts.
Let's look at an example of handling a button click. You create an event listener (OnClickListener) and assign it to the element. Logic is written inside the listener: moving to another screen, calculating data or changing text. Important remember that all interactions with the UI must occur in the main thread (Main Thread), otherwise the application will freeze.
// Example on Kotlin
val myButton = findViewById
A common mistake is trying to find an element before calling setContentView. If you try to find a view by ID before loading the markup, the application will crash with a NullPointerException or similar error. Always load the XML first, and only then look for elements within it.
The setContentView method binds the Java/Kotlin code to the XML file. Without this call, the screen will remain blank, even if the Activity is running.
Navigation between screens (Intents)
To move from one screen to another, Android uses a mechanism Intents (Intents). These are message objects that contain information about which Activity needs to be launched. You create an Intent instance, specifying the context (the current Activity) and the class of the target Activity, and then pass it to the method startActivity.
Often you need to pass data to a new screen, for example, a user login or product ID. To do this, "Extras" are added to the Intent - key-value pairs. On the receiving side, this data is retrieved from getIntent. This allows you to make screens universal: the same Activity can display information about different users depending on the parameters passed.
- ๐ Explicit Intent โ exact indication of the target class (used within the application).
- ๐ Implicit Intent โ request for an action (for example, โopen a websiteโ) that the system performs.
- ๐ Result Intent โ return data back if the second screen should report something first.
There is also the concept of "Back Stack" (return stack). When you open a new Activity, it is placed on top of the previous one. Pressing the system Back button removes the top screen from the stack and returns the user to the previous one. You can manage this stack programmatically by closing the current screen or clearing the navigation history, which is useful when exiting the application or after successful authorization.
โ ๏ธ Warning: Transferring large amounts of data through Intents (for example, images or long lists) can lead to a buffer overflow and crash the application (TransactionTooLargeException). For large data, use databases or Singleton objects.
Frequently asked questions (FAQ)
Why doesn't Android Studio see my new Activity?
Most likely, you forgot to register it in the file AndroidManifest.xml. Check if the tag <activity android:name=".YourActivity">is there. Also make sure that the package name in the code matches the declared package.
What is the difference between an Activity and a Fragment?
An Activity is a full-fledged screen with its own life cycle. Fragment is a modular piece of UI that lives inside an Activity. Fragments allow you to create flexible interfaces, for example for tablets, where a list and details are displayed simultaneously on one screen.
How to transfer data back from the second screen to the first?
For this, the method is used startActivityForResult (in old APIs) or a more modern Activity Result API. The second screen should set the result via setResult and complete the work, and the first should process the data in the method.
Is it possible to create an Activity without an XML file?
Technically, yes, the entire interface can be designed programmatically in Java or Kotlin, creating View objects manually. However, this is highly discouraged as it complicates code maintenance and the separation of logic and appearance. XML is an industry standard.