当视图寻呼机对用户可见时,更新片段

时间:2015-10-04 18:54:06

标签: java android android-viewpager

我有50页需要不断更新当前片段,ChangeListener工作正常,但首先刷新不起作用,如何在用户看到片段刷新时实现片段刷新?

MyPagerAdapter adapter = new MyPagerAdapter(getChildFragmentManager(), data);
mViewPager.setAdapter(adapter);
int position = data.size() - 1;
adapter.getFragment(position).refresh();
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

    @Override
    public void onPageSelected(int position) {
        adapter.getFragment(position).refresh();
    }

    @Override
    public void onPageScrollStateChanged(int state) {}
});

PageAdapter

private class MyPagerAdapter extends FragmentStatePagerAdapter {

    private final List<DateTime> mData;
    private Map<Integer, PagerFragment> mMap = new HashMap<>();

    public MyPagerAdapter(FragmentManager fm, List<DateTime> data) {
        super(fm);
        mData = data;
    }

    @Override
    public Fragment getItem(int position) {
        return PagerFragment.newInstance(mData.get(position));
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        PagerFragment f = (PagerFragment) super.instantiateItem(container, position);
        mMap.put(position, f);
        return f;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
        super.destroyItem(container, position, object);
        mMap.remove(position);
    }

    @Override
    public int getCount() {
        return mData.size();
    }

    public PagerFragment getFragment(int position) {
        return mMap.get(position);
    }
}

1 个答案:

答案 0 :(得分:1)

第一个问题不正确,我需要&#34;更新片段,当它们在视图寻呼机上对用户可见时#34;我找到了答案:

修改

public abstract class PageFragment extends Fragment {

protected Boolean mVisibleToUserFlag = null;

@Override
public void onResume() {
    super.onResume();

    if (mVisibleToUserFlag != null && mVisibleToUserFlag) {
        onVisible();
    }
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);

    if (isVisibleToUser && (mVisibleToUserFlag == null || mVisibleToUserFlag == false)) {
        mVisibleToUserFlag = true;
        if (isResumed()) {
            onVisible();
        }
    } else if (!isVisibleToUser && mVisibleToUserFlag == null) {
        mVisibleToUserFlag = false;
    } else if (!isVisibleToUser && mVisibleToUserFlag) {
        onHide();
        mVisibleToUserFlag = false;
    }
}

@Override
public void onDestroyView() {
    super.onDestroyView();

    mVisibleToUserFlag = null;
}

/**
 * This method invoked when page stand visible to user.
 */
public abstract void onVisible();

/**
 * This method invoked then page change state visibility change to hidden.
 */
public abstract void onHide();

}