Jul 19, 2021

Button To New Activity -Open Another Activity Click On Button Android Studio - Androidpro.in

In this post we will learn how to open new activity click on button in android studio, when I press the button to go into another Activity. I use two activity first activity where show button for click and second activity is used for open new activity, for more explain watch video below.

Step – 1 Add this xml code in the main activity.xml

 
    <Button
        android:id="@+id/buttn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Button One"
        android:textColor="@color/white"
        android:textSize="30sp"
        android:textStyle="bold" />
 

 

Step – 2 Add this java code in the main activity.java

 
Button button = (Button) findViewById(R.id.buttn);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Intent intent = new Intent(MainActivity.this, SecondActivity.class);
        startActivity(intent);
 
    }
});
 

 

 

main activity.xml code like this

 
<?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">
 
    <Button
        android:id="@+id/buttn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:text="Button One"
        android:textColor="@color/white"
        android:textSize="30sp"
        android:textStyle="bold" />
 
 
</RelativeLayout>
 
 

 

main activity.java code like this

package in.app.androidpro.myapplication;
 
import androidx.appcompat.app.AppCompatActivity;
 
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
 
public class MainActivity extends AppCompatActivity {
    Button button;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        Button button = (Button) findViewById(R.id.buttn);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SecondActivity.class);
                startActivity(intent);
 
            }
        });
 
    }
}
 
 

 

Now your project is ready

Whatsapp Button works on Mobile Device only