Search code examples
androidandroid-fragmentsandroid-viewpagerandroid-tablayout

Saving the clicked fragment in TabLayout without ViewPager


I have a viewpager with 4 fragments in it. In one of the fragments I have other 4 fragments which are in a TabLayout without a ViewPager. How can I hold a reference to which was the last shown fragment in the TabLayout and show that particular one when the whole TabLayout is recreated? I also need to have the below functionality because I refresh fragments each time they are clicked.

    public class HistoryTabFragment extends BaseFragment {

    private static final String ARG_PARAM1 = "param1";
    public static final String GET_MY_HISTORY = HistoryTabFragment.class.getName() + ".my_history";

    FragmentTabHistoryBinding mBinder;
    Shop mShop;
    MyHistoryFragment myHistoryFragment;
    StandardHistoryFragment standardHistoryFragment;
    OpenAccountFragment openAccountFragment;
    BacklogFragment backlogFragment;

    public HistoryTabFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment HistoryTabFragment.
     */
    public static HistoryTabFragment newInstance(Shop shop) {
        HistoryTabFragment fragment = new HistoryTabFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_PARAM1, Parcels.wrap(shop));
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            Parcelable parcelable;
            parcelable = getArguments().getParcelable(ARG_PARAM1);
            mShop = Parcels.unwrap(parcelable);
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinder = DataBindingUtil.inflate(inflater, R.layout.fragment_tab_history, container, false);
        setUpTabLayout();
        bindWidgetWithEvent();
        return mBinder.getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        //sendActionToActivity(GET_MY_HISTORY, mShop);
        replaceFragment(myHistoryFragment);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    private void setUpTabLayout() {
        myHistoryFragment = MyHistoryFragment.newInstance(mShop);
        standardHistoryFragment = StandardHistoryFragment.newInstance(mShop);
        backlogFragment = BacklogFragment.newInstance(mShop);
        openAccountFragment = OpenAccountFragment.newInstance(mShop);

        mBinder.tabs.addTab(mBinder.tabs.newTab().setText(R.string.my_offers), true);
        mBinder.tabs.addTab(mBinder.tabs.newTab().setText(R.string.standard_offers));
        mBinder.tabs.addTab(mBinder.tabs.newTab().setText(R.string.backlog));
        mBinder.tabs.addTab(mBinder.tabs.newTab().setText(R.string.open_account));
    }

    private void bindWidgetWithEvent() {
        mBinder.tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setCurrentTabFragment(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                setCurrentTabFragment(tab.getPosition());
            }
        });
    }

    private void setCurrentTabFragment(int tabPosition) {
        switch (tabPosition) {
            case 0:
                replaceFragment(myHistoryFragment);
                break;
            case 1:
                replaceFragment(standardHistoryFragment);
                break;
            case 2:
                replaceFragment(backlogFragment);
                break;
            case 3:
                replaceFragment(openAccountFragment);
                break;
        }
    }

    private void replaceFragment(Fragment fragment) {
        FragmentManager fm = getChildFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.frame_container, fragment);
        ft.addToBackStack(null);
        ft.commit();
    }

    @Override
    protected void setTypeface() {

    }

    private void sendActionToActivity(String action, Shop shop) {
        if (mListener == null) {
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putString(Constants.ACTION_KEY, action);
        bundle.putParcelable(Constants.DATA_KEY_1, Parcels.wrap(shop));
        mListener.onFragmentInteraction(bundle);
    }
}

Solution

  • I've done it. I save the position of the last clicked tab in SharedPreferences and then in onViewCreated I get the position and with a switch statement and I replace the correct fragment.

    public class HistoryTabFragment extends BaseFragment {
    
    private static final String ARG_PARAM1 = "param1";
    private static final String CURRENT_FRAGMENT = ".current_fragment";
    private static final String CURRENT_TAB = ".current_tab";
    
    FragmentTabHistoryBinding mBinder;
    Shop mShop;
    Fragment mFragment;
    PreferenceAdapter mPreferenceAdapter;
    int tabPosition;
    
    public HistoryTabFragment() {
        // Required empty public constructor
    }
    
    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment HistoryTabFragment.
     */
    public static HistoryTabFragment newInstance(Shop shop) {
        HistoryTabFragment fragment = new HistoryTabFragment();
        Bundle args = new Bundle();
        args.putParcelable(ARG_PARAM1, Parcels.wrap(shop));
        fragment.setArguments(args);
        return fragment;
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            Parcelable parcelable;
            parcelable = getArguments().getParcelable(ARG_PARAM1);
            mShop = Parcels.unwrap(parcelable);
        }
    }
    
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinder = DataBindingUtil.inflate(inflater, R.layout.fragment_tab_history, container, false);
        mPreferenceAdapter = new PreferenceAdapter(getContext());
        setUpTabLayout();
        bindWidgetWithEvent();
        return mBinder.getRoot();
    }
    
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        tabPosition = mPreferenceAdapter.readLastHistoryTabPosition();
        switch (tabPosition) {
            case 0:
                mFragment = MyHistoryFragment.newInstance(mShop);
                mBinder.tabs.getTabAt(tabPosition).select();
                replaceFragment(mFragment);
                break;
            case 1:
                mFragment = StandardHistoryFragment.newInstance(mShop);
                replaceFragment(mFragment);
                mBinder.tabs.getTabAt(tabPosition).select();
                break;
            case 2:
                mFragment = BacklogFragment.newInstance(mShop);
                replaceFragment(mFragment);
                mBinder.tabs.getTabAt(tabPosition).select();
                break;
            case 3:
                mFragment = OpenAccountFragment.newInstance(mShop);
                replaceFragment(mFragment);
                mBinder.tabs.getTabAt(tabPosition).select();
                break;
        }
    }
    
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        getChildFragmentManager().putFragment(outState, CURRENT_FRAGMENT, mFragment);
        outState.putInt(CURRENT_TAB, mBinder.tabs.getSelectedTabPosition());
    }
    
    private void setUpTabLayout() {
        mBinder.tabs.addTab(mBinder.tabs.newTab().setText(R.string.my_offers));
        mBinder.tabs.addTab(mBinder.tabs.newTab().setText(R.string.standard_offers));
        mBinder.tabs.addTab(mBinder.tabs.newTab().setText(R.string.backlog));
        mBinder.tabs.addTab(mBinder.tabs.newTab().setText(R.string.open_account));
    }
    
    private void bindWidgetWithEvent() {
        mBinder.tabs.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                setCurrentTabFragment(tab.getPosition());
            }
    
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
    
            }
    
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                setCurrentTabFragment(tab.getPosition());
            }
        });
    }
    
    private void setCurrentTabFragment(int tabPosition) {
        switch (tabPosition) {
            case 0:
                mFragment = MyHistoryFragment.newInstance(mShop);
                replaceFragment(mFragment);
                break;
            case 1:
                mFragment = StandardHistoryFragment.newInstance(mShop);
                replaceFragment(mFragment);
                break;
            case 2:
                mFragment = BacklogFragment.newInstance(mShop);
                replaceFragment(mFragment);
                break;
            case 3:
                mFragment = OpenAccountFragment.newInstance(mShop);
                replaceFragment(mFragment);
                break;
        }
        mPreferenceAdapter.writeLastHistoryTabPosition(mBinder.tabs.getSelectedTabPosition());
        mPreferenceAdapter.apply();
    }
    
    private void replaceFragment(Fragment fragment) {
        FragmentManager fm = getChildFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.frame_container, fragment);
        ft.addToBackStack(null);
        ft.commit();
    }
    }