0

I use ViewPager and Tabs. I have 3 tabs and in the first tab (Tab_1) I switch from FragmentA to FragmentB. Then I pass to the second tab (Tab_2). After that I return to Tab_1. Actually, it is the fragmentB that is showing but I want fragmentA to show when I return from Tab_2 to Tab_1. I want to have the same behavior when in tab1, I switch from FragmentA to FragmentB and if I pass to Tab_3 and return to Tab_1, it is the FragmentA that is showing. How can I do that?

Yoyo
  • 1
  • 2

3 Answers3

0

Did you try SetCurrentItem(int i) for ViewPager on Call of OnResume()

Sahan Monaara
  • 55
  • 1
  • 8
0

in mainActivity add addtoBackStack method.follow below code.

private void loadfragment(Fragment fragment) {

        FragmentManager fragmentManager = getFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(R.id.frame, fragment);
fragmentTransaction.addToBackStack("");

        fragmentTransaction.commit();

    }

    public void onBackPressed() {

        if (getFragmentManager().getBackStackEntryCount() > 0) {
            getFragmentManager().popBackStackImmediate();
        } else {

            super.onBackPressed();
        }
shizhen
  • 12,251
  • 9
  • 52
  • 88
  • I already add this method but my problem is not about the back button, but with side by side tabs – Yoyo Jan 26 '18 at 11:54
0

You can create a baseFragment which handles the back press navigation logic and extends that fragment to your fragment

public abstract class BackStackFragment extends Fragment {
    public static boolean handleBackPressed(FragmentManager fm)
    {
        if(fm.getFragments() != null){
            for(Fragment frag : fm.getFragments()){
                if(frag != null && frag.isVisible() && frag instanceof BackStackFragment){
                    if(((BackStackFragment)frag).onBackPressed()){
                        return true;
                    }
                }
            }
        }
        return false;
    }

    protected boolean onBackPressed()
    {
        FragmentManager fm = getChildFragmentManager();
        if(handleBackPressed(fm)){
            return true;
        } else if(getUserVisibleHint() && fm.getBackStackEntryCount() > 0){
            fm.popBackStack();
            return true;
        }
        return false;
    }

}

https://medium.com/@nilan/separate-back-navigation-for-a-tabbed-view-pager-in-android-459859f607e4

In above link, they have explained how to handle the tablayout and the back navigation of tablayout and change the fragment on backpressed

Kajol Chaudhary
  • 257
  • 2
  • 9
  • Kajol Chaudhary, while this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. [Answers that are little more than a link may be deleted.](//stackoverflow.com/help/deleted-answers) – 4b0 Jan 29 '19 at 06:28