Button Set On Click Listener To New Activity In Android Studio - Androidpro.in

 (Button To New Activity) Open Another Activity Using Button In Activity

 

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.

 

Xml Code

    <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" />

Java Code

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);

    }
});

 

 

Step 1. Create A project

Step 2.  Paste Code In Xml File Which Code Provide Below

<?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>

 

Step 3.  Create New Activity As You Want To Open Click On Button

Step 4.  Paste Java Code In Java File Which Code Provide Below

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 Done Project To Open New Activity Click On Button In Activity.