Developing a mobile application begins with navigation, and the most basic element of the interface is a button that switches the user between different screens. In the environment Android Studio this process is implemented through a combination of XML markup and logic in the programming language Kotlin or Java. Understanding the switching mechanism Activity or fragments is critical to creating any complex application, be it a simple calculator or a social network.
Many beginners encounter difficulties when trying to associate a graphical element with an action, because they forget to register components in the manifest or incorrectly pass the context. We will analyze not only the standard method through Intent, but also modern approaches using Jetpack Navigation, which are becoming an industry standard. Correct implementation of navigation ensures smooth operation and prevents memory leaks.
Preparing the project and creating a layout
The first step is to design the user interface where the button itself will be placed. In Android Studio, this is done in markup files with the extension .xml, located in the folder res/layout. You need to add an element Button or MaterialButton, assigning it a unique identifier that will allow you to access it from code.
Please note that the use of modern design material libraries, such as Material Components, makes the interface more attractive and compliant with Google guidelines. To do this, ConstraintLayoutis often used in the root element of the layout, which allows you to flexibly position elements relative to each other and the edges of the screen without using outdated nested groups.
When creating markup, it is important to immediately think through the resource naming structure. It is good practice to use prefixes, for example btn_login or btn_next, which makes the code easier to read in large projects. Don't forget to also add a text description for people with disabilities using the attribute android:contentDescription.
- ๐ฑ Be sure to set the button attribute
android:idto connect with the logic. - ๐จ Use
MaterialButtoninstead of the standardButtonfor modern type. - ๐ค Add resource strings to
strings.xml, rather than hard-code the text in XML. - ๐ Check the padding and size so that the button is easy to press with your finger.
Use the "Blueprint" tool in Android Studio layout editor to visually evaluate the layout of elements on different screen sizes before launching the application.
Setting up a second activity in the Manifest
Before writing transition code, the Android system must know about the existence of the screen you plan to navigate to. This is done by registering a new class Activity in a file AndroidManifest.xmlthat is located in the folder app/manifests. Without this entry, attempting to launch will cause the application to crash with an error ActivityNotFoundException.
Open the manifest and add the tag <activity> inside the tag <application>. In the attribute android:name specify the full name of the class of your new activity, or use the shorthand notation with a dot at the beginning if the class is in the same package. This action makes the component visible to the operating system.
โ ๏ธ Warning: If you forget to add an activity to the manifest, the application will compile successfully, but will crash immediately after clicking the button during execution.
It is also worth paying attention to the attribute android:label, which sets the screen title displayed in the top panel (Action Bar) or in the list of recent applications. The main activity usually has a flag set LAUNCHER, but for secondary screens this is not required unless you want them to appear as separate icons in the phone menu.
| Attribute | Value | Description |
|---|---|---|
android:name |
.SecondActivity |
Activity class name |
android:label |
@string/screen_two |
Screen title for the user |
android:parentActivityName |
.MainActivity |
Parent activity for upward navigation |
android:exported |
false |
Activity availability for other applications |
Implementation of transition through Intent in Kotlin
Logic switching screens is implemented inside the first activity class, usually in the onCreatemethod. The main task is to find a previously created button by its ID and attach a click handler to it. In the language Kotlin this is done concisely thanks to syntactic sugar and function findViewById or the use of View Binding.
For the transition itself, a class is used Intent, which acts as a message to the system about the intention to launch another component. The constructor Intent takes two main parameters: the context of the current screen (usually thisand the class of the target activity. After the intent object is created, the method is called startActivity.
button.setOnClickListener {val intent = Intent(this, SecondActivity::class.java)
startActivity(intent)
}
It is important to understand the difference between explicit and implicit intents. In this case, we use an explicit intent, since we know exactly the class that needs to be launched. Implicit intents are used for system actions, for example, opening a browser or dialing a number, where the system itself selects the appropriate application.
Transferring data between screens
Often there is a need not only to go to a new screen, but also to transfer some information there, for example, product ID, user name or calculation result. To do this, data is added to the object Intent before calling startActivity using the method putExtra. The data is packaged as key-value pairs.
On the receiving side, in the second activity, this data is retrieved in a method onCreate through an object intent. It is necessary to use appropriate receiving methods, such as getStringExtra, getIntExtra or getBooleanExtra, specifying the same key and default value in case the data is missing.
โ ๏ธ Attention: It is better to put keys for passing data into constants or a separate companion object to avoid typos in string literals that are difficult to catch during compilation.
If you need to pass a complex object, for example, a user model, the class of this object must implement the interface Serializable or Parcelable. Usage Parcelable is preferable in Android, as it is much faster and more efficient in terms of memory consumption, although it requires more boilerplate code to implement.
What is Parcelable?
It is an Android interface for object serialization, optimized for the mobile platform. Unlike standard Java Serializable, it avoids the use of reflection and creates fewer temporary objects, which is critical to UI performance.
Using the Jetpack Navigation Component
For complex applications with multiple screens, managing navigation through direct calls Intent becomes cumbersome and difficult to maintain. In such cases, it is recommended to use the architectural component Navigation from Google. It allows you to visualize the application flow in a special navigation graph and manage transitions declaratively.
Instead of creating many activities, modern applications often use one activity with several Fragment. Navigation Component simplifies working with fragments by automatically handling the back button and passing arguments between screens through a safe plugin Safe Argsthat generates type-safe classes for passing data.
- ๐บ๏ธ Visual navigation graph editor makes it easy to understand the structure of the application.
- ๐ Automatic processing of the "Back" button and deep links (Deep Links).
- ๐ก๏ธ Type-safe argument passing eliminates key errors.
- ๐ Reducing the amount of boilerplate code for fragment transactions.
Connecting this component requires adding several dependencies to the file build.gradle and creating a navigation file nav_graph.xml. Despite the initial complexity of the setup, in the long run this greatly facilitates refactoring and scaling the project.
Debugging and common errors
During the development process, you may encounter situations where a button is pressed, but nothing happens, or the application closes. The first step is to check the logs in the tool Logcat, where the system displays a detailed description of the exceptions. A common mistake is to try to access an interface element before the content has been loaded by the method setContentView.
Another common problem is context leakage. Never store activity context in static fields or long-lived objects, as this prevents the garbage collector from freeing memory after the screen closes. Use application context (applicationContext) where possible, or pass context only to the scope of the current screen.
โ๏ธ Diagnosing navigation problems
If you use View Binding or Data Binding, make sure the plugin is enabled in the build settings, otherwise the generated classes will not appear and the code will not compile. Also be careful not to call activity methods from a background thread, since all UI operations should be performed exclusively on the main thread.
Using Logcat is the fastest way to understand why your application is crashing. Look for red lines with the tag "AndroidRuntime" or the name of your package.
Frequently asked questions
How to pass data back to the previous screen?
To return data, use a method setResult in the second activity before closing it and processing the result in method onActivityResult first activity. However, in modern realities, common ViewModel or flow channels (Flow/StateFlow) are more often used to exchange data between screens.
What is the difference between an Activity and a Fragment?
An Activity is a separate application screen with its own life cycle and window. Fragment is a modular part of the interface that lives inside an Activity. Fragments allow you to create flexible interfaces, for example, for tablets, where several fragments are displayed on the same screen at the same time.
Why is the button not being clicked?
Perhaps there is another transparent element on top of the button (for example, an ImageView with a click enabled) that intercepts the event. Check the hierarchy in the Layout Inspector or add an attribute android:clickable="true" directly to the button.
Is it possible to open the screen in a new window (task)?
Yes, for this you need to add a flag FLAG_ACTIVITY_NEW_TASKto the Intent. This will create a new task in the application stack, and the back button will not lead to the previous screen of your application, but to the home screen or previous application.
How to animate the transition between screens?
Standard method startActivity does not accept animation parameters directly. You need to call startActivity(intent), and immediately after it the method overridePendingTransition(R.anim.enter_anim, R.anim.exit_anim), passing resources with animations.