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

PhD researcher at Friedrich-Schiller University Jena, Germany. I'm a physicist specializing in theoretical, computational and experimental condensed matter physics. I like to develop Physics related apps and softwares from time to time. Can code in most of the popular languages. Like to share my knowledge in Physics and applications using this Blog and a YouTube channel.



Leave a Reply

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