androidandroid-viewpagerandroid-tabsandroid-pageradapter

Refresh tab from another tab


I have an Activity that contains a ViewPager with four tabs . each tab has a fragment.

When I click something in tab 4, I want tab 3 to refresh(or access a non-static method in tab 3 ) ..I've searched but all I found had this in it:

FragmentB fragment = (FragmentB)getFragmentManager().findFragmentByTag("FragmentB");

and I can't use it since I never set a tag on the fragment.

I also could call a function from fragment in another fragment but it has to be static , and I don't want that since everything inside it must be static too and that would mess things up for me..

is there a solution to this ?


Solution

  • First of all i think it's not a good practice to update a view which user cannot see on screen at the moment. It's much better to update your data when user navigates to screen. By the way it not our first concern now.

    I'm not sure this is still a valid way to find Fragments in a ViewPager byTag but you can find them like below:

    This method generates default Tag for a Fragment in ViewPager.

    @NonNull
    public static String generateViewPagerFragmentTag(int viewPagerId, int position) {
        final StringBuilder tagBuilder = new StringBuilder();
        tagBuilder.append("android:switcher:");
        tagBuilder.append(viewPagerId);
        tagBuilder.append(":");
        tagBuilder.append(position);
        return tagBuilder.toString();
    } 
    

    Than you can use this tag to find your Fragment with findFragmentByTag method.

    Also as mentioned in comments you can use an EventBus library to achieve what you want to do but be careful of Fragment Lifecycle states in ViewPager because the Fragment you want to communicate can be in onPause state an your changes canned be received. This depends on in which lifecycle method you subscribe and unsubscribe to bus. (If you are using OttoBus you can get no subscribers found for this event exception.) You can do same pattern with interfaces. You can create an interface and implement in your Fragments.

    For an other solution, you can directly access our fragments in your ViewPager. Here's my answer for another question it.

    Finally, as i mentioned at the beginning i think you should implement a solution which updates your data when user switched to specific tab of ViewPager. You can keep your data changes in a mem-cache and listen tab changes and update your view when user exactly navigated to that screen and ready to see data changes. You can check Repository pattern for a more complex solution.