I have created an homepage with 2 buttons and i want to link the first button with the main activity and the second button with the main 2 activity. What Ihave to do?
Asked
Active
Viewed 50 times
0
-
Here you have the oficial "tutorial" on how to do it --> . https://developer.android.com/training/basics/firstapp/starting-activity.html?hl=es – Shudy May 24 '17 at 13:00
-
Possible duplicate of [How to open a second activity on click of button in android app](https://stackoverflow.com/questions/13194081/how-to-open-a-second-activity-on-click-of-button-in-android-app) – Opiatefuchs May 24 '17 at 13:03
3 Answers
1
Here is a basic example:
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(this,MainActivity.class);
}
});
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(this,Main2Activity.class);
}
});

Shudy
- 7,806
- 19
- 63
- 98
1
How to start new activity on button click
For instance, in onCreate() write:
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), Activity1.class);
view.getContext().startActivity(intent);}
});
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(view.getContext(), Activity2.class);
view.getContext().startActivity(intent);}
});

CoolMind
- 26,736
- 15
- 188
- 224
1
you can achieve this through xml too
<Button
android:id="@+id/button1"
android:layout_width="match_parent"
android:layout_height="@dimen/height"
android:layout_margin="@dimen/fields_margin_bottom"
android:text="Activity1"
android:textColor="@color/defaultTextColor"
android:textAllCaps="true"
android:textSize="@dimen/size"
android:onClick="mainActivty"/>
<Button
android:id="@+id/button2"
android:layout_width="match_parent"
android:layout_height="@dimen/height"
android:layout_margin="@dimen/fields_margin_bottom"
android:text="Activity2"
android:textColor="@color/defaultTextColor"
android:textAllCaps="true"
android:textSize="@dimen/size"
android:onClick="main2Activty"/>
And then implement those methods in your Homepage activity
public void mainActivty(View v) {
startActivity(new Intent(this,MainActivity.class);
}
public void main2Activty(View v) {
startActivity(new Intent(this,Main2Activity.class);
}

Ali Ahsan
- 460
- 3
- 13