how to open second activity in android example

If you are an expert or already know basics of android development then you already know how to open second activity from your mainactivity. But this tutorial will help all the beginners in android application development, In this tutorial we will explain you how to open second activity in android.

So Let's start the tutorial, First Create your project and also create second activity (SecondActivity.java)
in your project after that in your mainactivity.java file put the code below.

package com.activityapp.app;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.widget.Button;

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pledge);        
    }
    public void openSecondActivity(View v){
	startActivity(new Intent(this,SecondActivity.class));
    }
}

Now put the below code in your main activity layout xml file

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click Below Button to open second activity"
        android:textSize="25dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        />
   
    <Button
        android:layout_width="match_parent"
        android:layout_height="50dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginBottom="20dp"
        android:layout_alignParentBottom="true"
        android:text="Open Second Activity"
        android:textSize="20dp"
        android:textAllCaps="false"
        android:onClick="openSecondActivity" //here we call method
        />

</RelativeLayout>

By using this enough of code you can open any other activity from your main activity.
If you want to close your main activity on open of the second activity then call finish() method in your openSecondActivity method.

Happy Coding!
Thanks.

Comments