Android Development
Button Click Event
Start Activity
Mobile App Tutorial
Java Programming

How to start new activity on button click

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Android app development, activities play a crucial role in managing the user interface. An activity represents a single screen with a user interface—akin to a window or page in a desktop application. The most common interaction that requires creating or transitioning to a new activity is through a button click. This article explores how to start a new activity upon a button click using technical explanations and examples.

Understanding Activities and Intents

Activities in Android are essential building blocks of an Android app. Each activity usually interacts with the user and performs a specific task. To move from one activity to another, developers use Intents. An Intent is an abstract description of an operation to be performed, such as starting or switching to a different activity.

Intents in Android

An Intent is generally used to start activities and can be of two types:

  • Explicit Intents: Directly specifies the activity you want to start.
  • Implicit Intents: Describes an action to be performed, and the Android system determines the app component to fulfill that intent.

Steps to Start a New Activity on Button Click

Here’s a step-by-step guide to set up a transition to a new activity when a button is clicked.

Step 1: Set Up Your Activities

  1. Create your Main Activity: This will be the launch activity with a user interface that includes a button. For instance, MainActivity.
  2. Create the Second Activity:
    • Within your Android Studio project, create a new activity, say SecondActivity.
    • Define the UI layout for SecondActivity in a new XML file (e.g., activity_second.xml).

Step 2: Update Layout XML for Main Activity

You need to have a button in your activity_main.xml layout file:

xml
1<!-- activity_main.xml -->
2<Button
3    android:id="@+id/buttonStartNewActivity"
4    android:layout_width="wrap_content"
5    android:layout_height="wrap_content"
6    android:text="Start New Activity" />

Step 3: Define Intent in Main Activity

In MainAcitvity.java, create an Intent and start SecondActivity on the button click:

java
1// MainActivity.java
2package com.example.myapp;
3
4import android.content.Intent;
5import android.os.Bundle;
6import android.view.View;
7import android.widget.Button;
8
9import androidx.appcompat.app.AppCompatActivity;
10
11public class MainActivity extends AppCompatActivity {
12    @Override
13    protected void onCreate(Bundle savedInstanceState) {
14        super.onCreate(savedInstanceState);
15        setContentView(R.layout.activity_main);
16
17        Button button = findViewById(R.id.buttonStartNewActivity);
18        button.setOnClickListener(new View.OnClickListener() {
19            @Override
20            public void onClick(View v) {
21                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
22                startActivity(intent);
23            }
24        });
25    }
26}

Step 4: Declare New Activity in AndroidManifest.xml

Every activity in an Android app must be declared in the AndroidManifest.xml file:

xml
1<application ... >
2    <activity android:name=".MainActivity">
3        <intent-filter>
4            <action android:name="android.intent.action.MAIN" />
5            <category android:name="android.intent.category.LAUNCHER" />
6        </intent-filter>
7    </activity>
8    <activity android:name=".SecondActivity" />
9</application>

Additional Considerations

Passing Data Between Activities

If you need to pass data from MainActivity to SecondActivity, you can use Intent extras:

java
1// Passing data in MainActivity
2Intent intent = new Intent(MainActivity.this, SecondActivity.class);
3intent.putExtra("KEY", "value");
4startActivity(intent);
5
6// Receiving data in SecondActivity
7Bundle extras = getIntent().getExtras();
8if (extras != null) {
9    String value = extras.getString("KEY");
10}

Finish Activity

Optionally, when you start a new activity, you might want to finish the current one:

java
startActivity(intent);
finish();

This line of code, finish(), will close the current activity and remove it from the activity stack.

Summary Table

The table below summarizes the key points of starting a new activity via button click:

StepDescriptionKey Actions
1Create ActivitiesCreate Main and Second Activities. Define UI layout for both.
2Update Main LayoutAdd a Button element in activity_main.xml.
3Configure IntentSet up an Intent to start the new activity.
4Manifest DeclarationDeclare all activities in AndroidManifest.xml.
AdditionalPass Data Finish CurrentUse Intent extras to pass data. Use finish() if necessary.

Understanding how to navigate between activities is a foundational skill in Android development. Practicing these steps will ensure smooth transitions within your application and enhance the user experience.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.