android - ViewPager+Fragment,某个Fragment里面的一条数据发生变化,如何局部刷新这条数据
高洛峰
高洛峰 2017-04-17 17:42:05
0
4
678

ViewPager+Fragment,某个Fragment里面的一条数据发生变化,如何局部刷新这条数据

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(4)
巴扎黑

When the item of ViewPager is Fragment, FragmentPagerAdapter is generally used as the Adapter, and this class will be used when adding Fragment To add a tag, see the instantiateItem() method in the source code of FragmentPagerAdapterViewPager的item是Fragment时一般使用FragmentPagerAdapter作为Adapter, 而这个类在添加Fragment的时候会添加tag, 看FragmentPagerAdapter的源码中的instantiateItem()方法

@Override
public Object instantiateItem(ViewGroup container, int position) {
    // 省略
    if (fragment != null) {
        // 省略
    } else {
        // 省略部分代码
        // 下面这句就是添加Fragment的语句, 第三个参数就是指定Fragment的tag, 
        // 你可以利用这个tag获取到对应的Fragment实例, 有了实例就可以随意更新Fragment的视图了
        mCurTransaction.add(container.getId(), fragment,
                makeFragmentName(container.getId(), itemId));
    }
    // 省略
    return fragment;
}

这个tag是通过一个makeFragmentName()的私有方法获取, 不过只要把这个方法直接复制出来就可以了, 这个方法的参数viewId应该是ViewPager的id, itemId是adapter的getItemId() rrreee
This tag is obtained through a private method of makeFragmentName(), but you only need to copy this method directly. The parameter viewId of this method should be the id of ViewPager , itemId is the getItemId() method of the adapter, so you can assemble the tag yourself and get the Fragment.

That’s it.🎜
左手右手慢动作

If you use RecyclerView, you can use Eventbus like this

mAdapter.getItem(event.position).setCommentCount(mAdapter.getItem(event.position).getCommentCount()+1);
mAdapter.notifyItemChanged(event.position);
左手右手慢动作

I have also been thinking about this problem for a while, and after searching for it, I couldn’t find a good solution. The pagerfragmentadapter doesn’t seem to provide an API for getting the corresponding fragment.
I made a list of weak references in the index and added it to the adapter when it initialized the fragment, and then rewritten the adapter's onDestroyItem (probably called this? I can't remember) to remove the corresponding entry in the list here.
Once you get the fragment instance, you can operate it as you like.

Peter_Zhu
  1. When the Fragment is in the foreground, you can use LocalBroadcastManager / EventBus / otto / Rx to subscribe to an event (message)

  2. When the Fragment switches to the background, cancel the subscription. When the Fragment switches to the foreground again, refresh the page data and resubscribe

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template