How to Move from One Activity to Another in Android: A Simple Guide with Code Example

Arzath Areeff
3 min readMay 13, 2023

--

In Android app development, moving from one screen to another is a common feature.

The process of moving from one activity to another activity in Android is known as activity switching.

The code provided demonstrates how to switch from the MainActivity to the SecondActivity.

Main Activity

In the MainActivity, the onCreate() method is overridden to set the layout for the activity using the setContentView() method.

The buttonOB variable is used to store a reference to the ClickMeBtn button in the layout file using the findViewById() method.

ClickMeBtn

The setOnClickListener() method is then used to listen for a click event on the button.

When the button is clicked, an Intent is created to switch from MainActivity to SecondActivity using the intent constructor, and the startActivity() method is called to start the new activity.

MainActivity:
package com.example.parttime;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


private Button buttonOB;

@SuppressLint("MissingInflatedId")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonOB=findViewById(R.id.ClickMeBtn);

buttonOB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(MainActivity.this,SecondActivity.class);
startActivity(intent);
}
});
}

}

In the SecondActivity, the onCreate() method is overridden to set the layout for the activity using the setContentView() method.

package com.example.parttime;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class SecondActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
}
}

This code demonstrates the basics of activity switching in Android, which is essential for building multi-screen applications.

It is important to note that the second activity is created and started by the first activity, and the first activity remains active until the second activity is destroyed.

Second Activity

Overall, the code provided is a simple and effective way to switch from one activity to another activity in an Android app.

--

--

Arzath Areeff
Arzath Areeff

Written by Arzath Areeff

TechNomad🚀🎒 Founder of ideaGeek & digizen. Sharing passion for adventure, education, and positive impact. 🌳linktr.ee/rzomar

No responses yet