片段没有刷卡刷新

时间:2015-09-10 05:57:12

标签: android android-fragments android-viewpager

我正在使用viewPager将其滑动功能在两个片段之间滑动。但是我想在刷卡时刷新片段内容。 FragmentStatePagerAdapter在缓存方面表现非常出色,因此很难让Fragment重新加载。我已经尝试将所有内容放在onResume方法中,但这没有效果。

这是我的代码

slideadapter=new ScreenSlidePagerAdapter(this.getSupportFragmentManager());
    mViewPager = (ViewPager) findViewById(R.id.viewpager);
    mViewPager.setOffscreenPageLimit(1);

    mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
        @Override
        public void onPageScrolled(int i, float v, int i2) {
            //Not used
            Log.v("TAG","onPageScrolled");
        }

        @Override
        public void onPageSelected(int position) {
            //Force the fragment to reload its data
            Fragment f = slideadapter.getItem(position);
            f.onResume();
        }

        @Override
        public void onPageScrollStateChanged(int i) {
            //Not used
            Log.v("TAG","onPageScrollStateChanged");
        }
    });
    mSlidingTabLayout = (SlidingTabLayout)findViewById(R.id.sliding_tabs);
    mViewPager.setAdapter(slideadapter);

    mViewPager.setCurrentItem(0);

    mSlidingTabLayout.setViewPager(mViewPager);

3 个答案:

答案 0 :(得分:1)

您可以覆盖片段中的setUserVisibleHint方法

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

答案 1 :(得分:0)

使用ViewPager.onPageChangeListener:

viewPager.setOnPageChangeListener(new OnPageChangeListener() {
 public void onPageScrollStateChanged(int state) {}
 public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}

 public void onPageSelected(int position) {
    // get fragment by position and do whatever you want to do on fragment selection.
 }
});

答案 2 :(得分:0)

如果你想在片段变得可见的时候调用onresume方法,你可以尝试mViewPager.setOffscreenPageLimit(1);