Reload or notify Fragment's data in ViewPager

China☆狼群 提交于 2019-12-22 10:00:11

问题


I have [main]Fragment with two ViewPagers in it. Each ViewPager contains several Fragments in it. ViewPager's Fragments obtain data into their ListViews from [main]Fragment. I need to update data in all ListViews, which comes from [main]Fragment.


I've tried to remove current [main]Fragment and add new one (reload it), but when I am calling .remove([main]Fragment) or .detach([main]Fragment) methods in .supportFragmentManager() [main]Fragment is not destroying or detaching, it just hiding and I cant add new one, just make .atach([main]Fragment) for current... Reload activity is bad idea. Please help me.


回答1:


Content Observers

Here's a simple URI that the link doesn't show how to do. Put this in the class that does the data changes so any fragment can access it static via ClassName.CONTENT_URI.

private static final String BASE_PATH = "Imustdorefresh";//see content providers
private static final String AUTHORITY = "somethinguniquehereprobablyappcomname";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
            + "/" + BASE_PATH);

This code goes in fragments onresume see the link don't forget to unregister in onpause

getContentResolver().
      registerContentObserver(
            CONTENT_URI,
            true,
            yourObserver);

//yourObserver is code to refresh the fragment {do stuff here code}

In the piece of code that changes the data call the contentresolver notify method after every data change. The content resolver will call the registered observers in the fragments.

getContext().getContentResolver().notifyChange(CONTENT_URI,null);

For more information see content provider and content observer. For more details on a Content Provider



来源:https://stackoverflow.com/questions/25791664/reload-or-notify-fragments-data-in-viewpager

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