ViewPager+Fragment,某个Fragment里面的一条数据发生变化,如何局部刷新这条数据
巴扎黑2017-04-17 17:44:05
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 FragmentPagerAdapter
ViewPager
的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.
ringa_lee2017-04-17 17:44:05
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);
ringa_lee2017-04-17 17:44:05
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.
天蓬老师2017-04-17 17:44:05
When the Fragment is in the foreground, you can use LocalBroadcastManager / EventBus / otto / Rx to subscribe to an event (message)
When the Fragment switches to the background, cancel the subscription. When the Fragment switches to the foreground again, refresh the page data and resubscribe