gabriele.pacor
gabriele.pacor

Reputation: 107

Link 2 buttons with 2 different Activitys

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?

enter image description here

enter image description here

Upvotes: 0

Views: 55

Answers (3)

Ali Ahsan
Ali Ahsan

Reputation: 470

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

Upvotes: 1

CoolMind
CoolMind

Reputation: 28793

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

Upvotes: 1

Shudy
Shudy

Reputation: 7936

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

Upvotes: 1

Related Questions