InfZero
InfZero

Reputation: 3045

How to update a tab content in TabLayout component?

I have this app

TabLayout tabs

It shows a list of songs (1st tab), a list of videos, and a list of favorites, both, audios and videos.

When I update -add or remove- a video to/from favorites... and if I pass directly to the Favorites tab, the ListView doesn't refresh.

That ListView updates only when I go to the first tab -Audio- and then to the third one -Favorites-.

Details:

What I need to do to update the Favorites tab without going to the the first tab?

Upvotes: 0

Views: 633

Answers (1)

Ruann Reis
Ruann Reis

Reputation: 159

This happens because the fragments are created at same time with your activity, depending on some parameters, the layout of you third fragment is updated when you navigate to first tab because the view pager keeps the pages offscreen in a idle state and the default value is 1 to each side, you can set the value using:

mViewPager.setOffscreenPageLimit(value_that_you_want); //can't be less than 1

Example with value 1:

You have 3 fragments A - B - C.

  • When you start the activity you are at A, so the rigth fragment are B, then A and B will be created at once.
  • When you go to B you have one fragment each side, then C will be created.
  • When you go to C, the fragment A is two on the left side of C and will be destroyed, the same happens when you go back to A, B will be kept on idle and C (two on the right side of A) will be destroyed.

Main question

To refresh your third without going back to the first one, you will have implement a pageChangeListener to your viewPager and update what you want inside the listener

mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {

            if(position == 2){ // your third fragment are at position 2
               // update your UI here
            }
        }

        @Override
        public void onPageScrollStateChanged(int state) {

        }
    });

When your third fragment is selected, the code will be executed

Upvotes: 1

Related Questions