I was thinking of doing something similar to this but the opposite. Suppose I have a continue button in the parent activity's action bar. I have several fragments that should be displayed in order. How do I go to the next fragment by just clicking the continue button?
Asked
Active
Viewed 113 times
0
-
add new fragment to backstack. – kimkevin Dec 01 '17 at 09:41
-
@kimkevin, Thanks, but can you elaborate? I was thinking of creating a method that can be called inside the onClickListener of the continue button from the parent activity. Is that where I'm supposed to add the new fragment to the backstack? – Bargain23 Dec 01 '17 at 09:44
-
setOnClickListener to your view in parent Activity then you can add any fragment you want. show your code. – kimkevin Dec 01 '17 at 09:46
2 Answers
1
Using OnClick
of the Continue Button Just Replace or Add New Fragment to the Container
.
In Onclick
of Continue Button Do nested if else or switch:
Fragment f = getActivity().getFragmentManager().findFragmentById(R.id.fragment_container);
if (f instanceof FirstFFragmentClass) {
// do something with f
FragmentTransaction ft = getActivity().getFragmentManager().beginTransaction();
SecondFragmentClass secondFragment = new SecondFragmentClass();
ft.replace(R.id.fragment_container, secondFragment);
} else if (f instanceof SecondFragmentClass){
}

Tomin B Azhakathu
- 2,656
- 1
- 19
- 28
-
Thanks. I was wondering if `getActivity()` is still necessary while I'm in the actual activity? – Bargain23 Dec 01 '17 at 09:56
-
If you are in actual activity then you can avoid `getActivity()` – Tomin B Azhakathu Dec 01 '17 at 09:57
0
Call from your main activity a method that does:
Fragment myNewFragment = MyFragmentClass.newInstance();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_container, myNewFragment, "newTag");
transaction.addToBackStack(null);
transaction.commit();
Where R.id.fragment_container is a maybe a FrameLayout or other layout in your XML, myNewFragment is a Fragment returned by creating a new Fragment object or perhaps a custom method like newInstance() that you can pass an argument to use the same Fragment class but layout different views/text.

SHartley
- 37
- 4