Saturday, October 26, 2019

Open New Activity on Button Click in Android — Intent Tutorial

Activities are one of the most important building blocks in Android applications.

Every Android screen is usually represented by an:


Activity

In this tutorial, we will learn:

  • What an Activity is
  • How to open a new Activity
  • How Android Intent works
  • How to navigate between screens
  • How to register Activities in Manifest
  • Modern AndroidX implementation

What Is an Activity in Android?

An Activity represents a single screen with a user interface.

Examples:

  • Login screen
  • Home screen
  • Profile screen
  • Settings screen
  • Checkout screen

What Is an Intent?

Intent is a messaging object used for:

  • Opening activities
  • Starting services
  • Sending broadcasts
  • Sharing data between components

Types of Intents

Explicit Intent Implicit Intent
Targets specific Activity Targets external action
Inside app navigation Open browser, camera etc.

What We Will Build

In this example:

  • User clicks button
  • Intent created
  • Second Activity opens
  • User navigates to another screen

Important Modern Android Note

Older tutorials use:


android.support.*

which is deprecated.

Modern Android applications should use:


androidx.*

Step 1 — Create activity_main.xml

Create:


res/layout/activity_main.xml

Modern ConstraintLayout Version


<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout

    xmlns:android=
    "http://schemas.android.com/apk/res/android"

    xmlns:app=
    "http://schemas.android.com/apk/res-auto"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <TextView

        android:id="@+id/textView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Activity 1"

        android:textSize="24sp"

        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintEnd_toEndOf="parent"/>

    <Button

        android:id="@+id/button"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Open Activity 2"

        android:layout_marginTop="16dp"

        app:layout_constraintTop_toBottomOf="@id/textView"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Why Use ConstraintLayout?

ConstraintLayout provides:

  • Better rendering performance
  • Responsive layouts
  • Flat hierarchy
  • Flexible positioning

Step 2 — Create MainActivity.java


package com.example.openactivity;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Button;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity
        extends AppCompatActivity {

    private Button button;

    @Override
    protected void onCreate(
            Bundle savedInstanceState
    ) {

        super.onCreate(
                savedInstanceState
        );

        setContentView(
                R.layout.activity_main
        );

        button =
                findViewById(
                        R.id.button
                );

        button.setOnClickListener(
                view -> openActivity2()
        );
    }

    private void openActivity2() {

        Intent intent =
                new Intent(
                        MainActivity.this,
                        Activity2.class
                );

        startActivity(intent);
    }
}

Understanding Intent


Intent intent =
        new Intent(
                MainActivity.this,
                Activity2.class
        );

This creates an explicit intent targeting:


Activity2

What Does startActivity() Do?

The:


startActivity()

method launches the target activity.


Navigation Flow

  1. User clicks button
  2. Intent created
  3. Android resolves Activity
  4. Activity2 opens

Step 3 — Create activity_2.xml

Create:


res/layout/activity_2.xml

Modern activity_2.xml


<?xml version="1.0" encoding="utf-8"?>

<androidx.constraintlayout.widget.ConstraintLayout

    xmlns:android=
    "http://schemas.android.com/apk/res/android"

    xmlns:app=
    "http://schemas.android.com/apk/res-auto"

    android:layout_width="match_parent"

    android:layout_height="match_parent">

    <TextView

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:text="Activity 2"

        android:textSize="24sp"

        app:layout_constraintTop_toTopOf="parent"

        app:layout_constraintBottom_toBottomOf="parent"

        app:layout_constraintStart_toStartOf="parent"

        app:layout_constraintEnd_toEndOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Step 4 — Create Activity2.java


package com.example.openactivity;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

public class Activity2
        extends AppCompatActivity {

    @Override
    protected void onCreate(
            Bundle savedInstanceState
    ) {

        super.onCreate(
                savedInstanceState
        );

        setContentView(
                R.layout.activity_2
        );
    }
}

Step 5 — Register Activity in AndroidManifest.xml

Every Activity must be declared inside:


AndroidManifest.xml

Manifest Example


<application>

    <activity
        android:name=".Activity2"/>

    <activity
        android:name=".MainActivity">

        <intent-filter>

            <action
                android:name=
                "android.intent.action.MAIN"/>

            <category
                android:name=
                "android.intent.category.LAUNCHER"/>

        </intent-filter>

    </activity>

</application>

Why Manifest Registration Is Important

If Activity is not registered:

  • Application crashes
  • Android cannot resolve Intent
  • Navigation fails

Explicit Intent vs Implicit Intent

Explicit Intent Example


Intent intent =
        new Intent(
                this,
                Activity2.class
        );

Implicit Intent Example


Intent intent =
        new Intent(
                Intent.ACTION_VIEW
        );

Passing Data Between Activities

Intent also supports data transfer.


Example — Pass Data


intent.putExtra(
        "username",
        "Salil"
);

Retrieve Data in Activity2


String username =
        getIntent().getStringExtra(
                "username"
        );

Modern Android Recommendations

Modern Android applications commonly use:

  • Navigation Component
  • Safe Args
  • Single Activity Architecture
  • Fragments
  • Jetpack Compose Navigation

What Is Navigation Component?

Navigation Component simplifies:

  • Screen navigation
  • Back stack handling
  • Fragment transactions
  • Safe data passing

Jetpack Compose Alternative

Modern Android apps using Compose now use:


NavHost

and:


Composable navigation

Common Beginner Mistakes

1. Forgetting Manifest Registration

Every Activity must be registered.


2. Using Deprecated Support Libraries

Always migrate to AndroidX.


3. NullPointerException

Always initialize Views correctly using:


findViewById()

Best Practices

  • Use AndroidX
  • Use Navigation Component
  • Keep Activities lightweight
  • Use MVVM architecture
  • Pass only necessary data

FAQ

What is an Activity?

An Activity represents a single Android screen.


What is an Intent?

Intent is used for communication between Android components.


Why register Activity in Manifest?

Android needs Manifest registration to launch activities.


Conclusion

Opening a new Activity using Intent is one of the most fundamental concepts in Android development.

It enables screen navigation, modular UI architecture, and communication between application components.

Modern Android applications should combine AndroidX, Navigation Component, MVVM architecture, and scalable UI design for production-grade development.


About the Author

Salil Jha is a Full Stack and Mobile Developer specializing in Android, React Native, fintech systems, scalable SaaS platforms, and developer tooling products.

CodeChain Dev — Build Modern Products. Solve Real Problems.

No comments:

Post a Comment