user6333114 user6333114 - 6 months ago 13
Java Question

How do i get a button to open a new activity in android studio?

I'd seen this asked in many, many places and have tried to follow the instructions given to no avail. I dont know if the questions are old, i'm doing things incorrectly or if my android studio program isnt working. What i want to do is to only open a new activity when a button is clicked. I'm very new to developing android applications.

I've recently tried to follow the answer provided here: How do I get a button to open another activity in Android Studio?

OnClick on the button is called "goTutorials"
My original activity is called home (Not mainActivity)
The new one is called tutorials.

This is what i added from trying to follow the link above:
In home's java file:

btn = (Button)findViewById(R.id.open_activity_button);

btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(home.this, tutorials.class));
}
});


In manifest file:

<activity
android:name="tutorials"
android:label="@string/app_name">
</activity>

Answer

Method 1


Use the onclick attribute in XML (so that whenever you click the button, defined method will trigger)

Step 1. - go to the XML where you button is(activity_home) & add

<Button
............
android:onClick="gotoTutorial"/>

Step 2. - then go to the home.Java & add following

public void gotoTutorial(View v){
    Intent tutorialPage = new Intent (this, tutorials.class);
    startActivity(tutorialPage);
}

Method 2

Use the setOnClickListener

Step 1. -

 //create the link to the button in the interface
 btn_tutorial = (Button)findViewById(R.id.tutorial_button); 

 btn_tutorial.setOnClickListener(new View.OnClickListener() {
    @Override
        public void onClick(View v) {
            Intent tutorialPage = new Intent (this, tutorials.class);
            startActivity(tutorialPage);
        }
}