Skip to content
Advertisement

Call method from Fragment in unselected tab

I have an application with tabs. I use ViewPager and TabLayout. In each tab I have a Fragment. When the tab is unselected I want to call a method from the fragment in that tab.

If I want to call method on selected fragment i will do:

tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                String tag = "android:switcher:" + viewPager.getId() + ":" +  viewPager.getCurrentItem();
                Fragment f = getSupportFragmentManager().findFragmentByTag(tag);
                ((MyFragment) f).someMethod();
            }

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

            }

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

            }
        });

based on the How to know Fragment id for the fragment(s) provided by the tabbed activity template

But the problem is, that I don’t know how to do it on unselected tab.

Can you help me with this?

Advertisement

Answer

you can try run your code in onTabUnselected method, but be aware that this fragment may be destroyed in a next step.

        @Override
        public void onTabUnselected(TabLayout.Tab tab) {
            // tag for tab position
            String tag = "android:switcher:" + viewPager.getId() + ":" +  tab.getPosition();
            Fragment f = getSupportFragmentManager().findFragmentByTag(tag);
            if(f instanceof MyFragment) {
                ((MyFragment) f).someMethodWhenUnselecting();
            }
        }

also remember that ViewPager keeps in memory only current and one Fragment to the left and one to the right of current. so if you moving from e.g. 5 position to 4 then position 3 and below aren’t existing

pozdrowienia

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement