how to update fragement data when swiching Tabs

北慕城南 提交于 2019-12-12 00:46:50

问题


I am using Material Tab that I used 3 tabs.

Tab A [ Product List ]

Has a Recycle list and data populating from remote Server. For ex, it has Product title, image and favorite image

Tab B [ Favorite Product List ]

Tab C [ Contact Us ]

What I try to implement, Once user select on favorite button ( add to favorite ) that particular list item show in TAB_B [ Favorite Product List ]

I have used shared preference and save data as Gson format. I have followed this tutorial

http://androidopentutorials.com/android-how-to-store-list-of-values-in-sharedpreferences/

The issue is, once I add Item and remove item from Product List [ Tab A ] perform well, and it is not showing at Tab B [ Favorite Product List ]. Once I restart the app Favorite Product List is showing at Tab b. I used some tricks like broadcast receivers kind of things but it is not working correctly.

I use it.neokree:MaterialTabs:0.11 library to populate tabs

Here is my some codes that I have been used.

Please guide me, where I did wrong.


回答1:


  1. add compile 'org.greenrobot:eventbus:3.0.0' in gradle file
  2. In every fragment add in onCreate()

            EventBus.getDefault().register(this);
    
  3. In every fragment add in onDestroyView

            EventBus.getDefault().unregister(this);
    
  4. Create Java class for Event Example:

              public class EventUpdateList {
    
                private boolean listNeedUpdate= true;
    
                public EventUpdateList (boolean listNeedUpdate) {
                    this.listNeedUpdate= listNeedUpdate;
                }
    
                public boolean isListNeedUpdate() {
                    return listNeedUpdate;
                }
    
            }
    
  5. In all fragments add

       @Subscribe(threadMode = Main)
        public void onListRefresh(EventUpdatelist eventUpdateList) 
        {
           if (eventUpdateList.isNeedListUpdate) 
        {
        // refresh your list
    
        }
    
        } 
    
  6. In your activity add

    EventBus.getDefault.post(new EventUpdateList(true));
    

And all 3 fragments getting information about event to refresh list. You can even post Event with full list to refresh instead of this boolean and get in 3 fragments.




回答2:


Since the lib you're using basically uses ViewPager under the hood to manage given Fragment as Tab so this setUserVisibleHint method of Fragment should be the place you can update your tab content every time it loads.

public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (isVisibleToUser) {
              // Do stuffs that you want to do every time this fragment loads
        } else {
        }
}


来源:https://stackoverflow.com/questions/39018098/how-to-update-fragement-data-when-swiching-tabs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!