问题
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:
- add
compile 'org.greenrobot:eventbus:3.0.0
' in gradle file In every fragment add in onCreate()
EventBus.getDefault().register(this);
In every fragment add in onDestroyView
EventBus.getDefault().unregister(this);
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; } }
In all fragments add
@Subscribe(threadMode = Main) public void onListRefresh(EventUpdatelist eventUpdateList) { if (eventUpdateList.isNeedListUpdate) { // refresh your list } }
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