Search code examples
androidandroid-fragmentsandroid-viewpagerandroid-spinner

Correct way to attach an item selected listener with a spinner in a fragment attached with viewpager


I have 4 fragments attached with a viewpager. The 1st fragment has a spinner that has an item selected listener in onCreateView() method. Each time an item is picked from the spinner, a list adds that data.

Now when I swipe right to get to the other fragments, the 1st fragment is paused. Then if I come back to the 1st fragment the onCreateView() method runs again and loads the item selected listener again and adds the previosly added data again.

To avoid the situation I've taken the item selected listener inside an on touch listener. Now It's working as expected. But it just does not feel right. Any advice or help will be appreciated.

Thanks in advance.


Solution

  • Use this like this:

        viewPager = (ViewPager) findViewById(R.id.viewpager);
        viewPager.setOffscreenPageLimit(4); // 4 used for number of fragments like you are using 4 fragments using viewpager.
    

    This setOffscreenPageLimit will not refresh your fragment again and again.