How to open an Activity on the Press of a Button? [Solution] (Android Development)


To open a new Activity on the click of a button, just add the following method to your activity,

public void button_click(View view) {
        Intent intent = new Intent(this, ActivityName.class); //ActivityName is the name of the activity you want to launch on button click
        startActivity(intent);
    }

and call it when the button is pressed by adding the following line(attribute) to the button in your xml/layout file:

android:onClick="button_click"

Alternatively, instead of the above solution, you could just create an object of Button type and then define an OnClickListener as shwon below:

Button button=(Button)findViewById(R.id.button);

button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            Intent intent = new Intent(this, ActivityName.class); //ActivityName is the name of the activity you want to launch on button click
        startActivity(intent);
            }
        });
[wpedon id="7041" align="center"]

Leave a Reply

Your email address will not be published. Required fields are marked *

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