ViewPager使用FragmentPagerAdapter滑动Fragment动态加载Atlas bundle不显示问题

问题描述

ViewPager使用FragmentPagerAdapter滑动Fragment,然后通过Atlas插件化框架在Fragment的onCreateView中动态加载bundle,发现只显示第一个bundle,往后滑动ViewPager,能够正常加载Fragment,但不能显示Fragment的挂载的bundle。

这是FragmentPagerAdapter的加载机制引起的,为了让客户有更好的体验,当我们使用ViewPager显示一个Fragment的时候,FragmentPagerAdapter会自动加载其两侧的Fragment。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
FragmentPagerAdapter fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}

@Override
public int getCount() {
return mFragmentList.size();
}
};
mViewPager.setAdapter(fragmentPagerAdapter);
mViewPager.setOffscreenPageLimit(5);
mViewPager.addOnPageChangeListener(this);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
initDelegate(view, savedInstanceState);
return view;
}

private void initDelegate(View view, Bundle savedInstanceState) {
mActivityDelegate = new ActivityGroupDelegate(getActivity(), savedInstanceState);
mActivityGroupContainer = (ViewGroup) view.findViewById(R.id.content);
if (getActivity() != null) {
AtlasDelegateHelper.switchToActivity(getActivity(), mActivityDelegate, mActivityGroupContainer,
"home", "cn.appblog.home.ui.activity.HomeActivity");
}
}

解决方法

复写Fragment的setUserVisibleHint方法,在Fragment显示时动态加载

1
2
3
4
5
6
7
8
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser && getActivity() != null) {
AtlasDelegateHelper.switchToActivity(getActivity(), mActivityDelegate, mActivityGroupContainer,
"home", "cn.appblog.home.ui.activity.HomeActivity");
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :