How to Start New Activity on Button clicked in Android

One of the common questions beginner android developers ask when they start learning about android is how to start new activity on button clicked in android.

The easy way android use to open new activity when a button is clicked is by using Android Intent class. The code below shows a simple example.

activity_start_button.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="24dp">

    <Button
        android:id="@+id/startactivity"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/colorAccent"
        android:layout_centerInParent="true"
        android:text="Start Activity"
        android:drawableTint="#ffffff"
        android:textColor="#ffffff"
        android:textStyle="bold"
        android:textSize="15sp"/>

</RelativeLayout>

StartButtonActivity.java

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

import com.bluapp.androidview.R;

public class StartActivityButtonActivity extends AppCompatActivity {

    private Button startactivityBtn;

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

        startactivityBtn =(Button) findViewById(R.id.startactivity);

        startactivityBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(StartActivityButtonActivity.this, MainActivity.class));
            }
        });
    }
}

If you have any questions or suggestions kindly use the comment box or you can contact us directly through our contact page below.

 

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.