I have 2 activity and 2 fragment. In first activity there are 2 buttons and onClick of those buttons i want to add separate fragments to second activity. Like on click of btn1 open fragment 1 and onclick of btn2 open fragment 2 and attach to the second activity.
Asked
Active
Viewed 208 times
-3
-
Just pass a value . See [How do I pass data between Activities in Android application?](https://stackoverflow.com/questions/2091465/how-do-i-pass-data-between-activities-in-android-application). – ADM Jul 12 '18 at 05:28
-
What if there are 20 buttons? pass a value and check with if else or switch statement?? – Suman Razz Jul 12 '18 at 05:31
2 Answers
1
you have to pass flag from 1 activity to 2 activity. and put condition on 2 activity. like below ,
this for button 1
Intent intent = new Intent(view.getContext(), Activity2.class);
intent.putExtra("key", "button1");
startActivity(intent);
this for button 2
Intent intent = new Intent(view.getContext(), Activity2.class);
intent.putExtra("key", "button2");
startActivity(intent);
second activity
String click = new Intent.getStringExtra("key");
if(click.equal("button1")){
FragmentManager fragmentManage = getSupportFragmentManager();
fragmentManage.popBackStack();;
fragmentManage.beginTransaction().add(R.id.framLayout, new FragmentTab_One()).commit();
} else if(click.equal("button2")){
FragmentManager fragmentManage = getSupportFragmentManager();
fragmentManage.popBackStack();;
fragmentManage.beginTransaction().add(R.id.framLayout, new FragmentTab_Second()).commit();
}

Ravi Patel
- 309
- 2
- 13
-
your solution helped pretty much,but if number of button increases, is there any way we can do it by defining a method and passing a fragment as parameter on the onClick method of button – Suman Razz Jul 12 '18 at 05:57
-
-
They are static buttons,but i want to add more buttons each for a specified fragment – Suman Razz Jul 12 '18 at 07:59
0
on button click of first and second pass different value in Intent and start Second Activity.
When you reach to Second Activity check the value gated from first Activity.create if condition to check value and based on Condition call Fragment.

Bhavik Makvana
- 1
- 1