我有一个 ViewPager为4个标签的片段,在第四个标签中我有另一个带有3个标签的Viewpager,以便每当我切换我的topviewPagerTab时(一个有4个选项卡)然后子视图中的片段的setUserVisiblehint(带有3个选项卡)不被称为。
所以实际上,第4个/最后一个标签的sub viewPager中的片段对于用户是不可见的,但是 setUserVisibleHint()没有被调用,因此我的布尔值 isMyPageVisible被设置为除非我在subviewPager
中切换标签,否则访问该片段对他们来说总是如此boolean isPageVisible = false;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
isPageVisible = isVisibleToUser;
}
答案 0 :(得分:1)
public class UserAdapter extends FragmentPagerAdapter
{
private ArrayList<Fragment> fragments;
public UserAdapter(FragmentManager fm, ArrayList<Fragment> fragments)
{
super(fm);
this.fragments = fragments;
}
public void clearFragment()
{
fragments.clear();
}
@Override
public Fragment getItem(int position) {
return fragments.get(position);
}
@Override
public int getCount() {
return fragments.size();
}
public void setUserVisibleHint(boolean isUserVisibleHint)
{
if(viewPagerPojos != null && viewPagerPojos.size() > 0)
{
for(ViewPagerPojo viewPagerPojo : viewPagerPojos)
{
viewPagerPojo.getFragment().setUserVisibleHint(isUserVisibleHint);
}
}
}
}
并在每个片段中
@Override
public void setUserVisibleHint(boolean isVisible) {
super.setUserVisibleHint(isVisible);
if (mAdaptor != null) {
mAdaptor.setUserVisibleHint(isVisible);
}
}
和子片段
boolean isPageVisible;
@Override
public void setUserVisibleHint(boolean isVisibleHint)
{
isPageVisible = this.isVisible() && isVisibleHint;
super.setUserVisibleHint(isPageVisible);
}
答案 1 :(得分:0)
问题在于,当您在外部片段之间移动时,不会调用内部viewpager中显示的当前片段的setUserVisibleHint。 扩展FragmentStatePagerAdaptor
public class CustomPagerAdaptor extends FragmentStatePagerAdaptor {
private Fragment primary;
@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
primary = (Fragment)object;
}
public void setUserVisibleHint(boolean isVisible) {
if (primary != null){
primary.setUserVisibleHint(isVisible);
}
}
}
在外部片段中通过setUserVisibleHint传递:
@Override
public void setUserVisibleHint(boolean isVisible) {
super.setUserVisibleHint(isVisible);
if (mAdaptor != null) mAdaptor.setUserVisibleHint(isVisible);
}