ViewPager.setOffscreenPageLimit(0)完全没有效果。如何在ViewPager中一次只加载一个页面?

时间:2013-07-30 13:40:13

标签: java android android-viewpager

即使我设置了oViewPager.setOffscreenPageLimit(0),我的视图寻呼机仍会在可见页面的每一侧加载1个屏幕页面。

如何在用户滑动页面时加载页面?

我的适配器如果有帮助:

public class MainPagerAdapter extends FragmentPagerAdapter {
    protected static final String[] CONTENT = new String[] { "page 1", "page 2", "page 3", "page 4", };

    private int mCount = CONTENT.length;

    public MainPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        //return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
        return MainFragment.newInstance(position);
    }

    @Override
    public int getCount() {
        return mCount;
    }

    @Override
    public CharSequence getPageTitle(int position) {
      return MainPagerAdapter.CONTENT[position % CONTENT.length];
    }

    public void setCount(int count) {
        if (count > 0 && count <= 10) {
            mCount = count;
            notifyDataSetChanged();
        }
    }


}

8 个答案:

答案 0 :(得分:5)

另一种方法是使用OnPageChangeListener,每当发生页面更改时,请在片段中调用刷新方法。

这将要求您设置更高的OffScreenPageLimit,但每次进入视图时片段都会更新。

pager.setOnPageChangeListener(new OnPageChangeListener() {

     @Override
     public void onPageSelected(int position){
         ((MyRefreshableFragment)pager.getAdapter().getItem(position)).refresh();
     }

     @Override
     public void onPageScrolled(int arg0, float arg1, int arg2) {}
     @Override
     public void onPageScrollStateChanged(int arg0) {}
  });

答案 1 :(得分:3)

  

如何在用户滑动页面时加载页面?

编写自己的ViewPager。正如Jani的回答所指出的那样,ViewPager每侧的最小屏幕外页面限制为1。

这是滑动动画平稳运行所必需的。否则,如果我们必须等待您为下一页设置用户界面,则用户的滑动将被冻结,或者滑动到空白内容,因为无论您需要多长时间才能建立该UI。

答案 2 :(得分:1)

你不能这样做。您将收到如下错误: “请求屏幕外页面限制0太小;默认为1”。但在这里你可以找到更多相关信息:ViewPager.setOffscreenPageLimit(0) doesn't work as expected

答案 3 :(得分:1)

几轮工作后,我找到了解决方案。这是完美的工作。 每个选项卡片段类均实现此代码步骤。

<android.support.design.widget.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="end|bottom"
    android:layout_margin="16dp"
    android:clickable="true"
    android:focusable="true"
    app:backgroundTint="@color/white"
    app:fabSize="normal"
    app:layout_dodgeInsetEdges="bottom"
    app:srcCompat="@drawable/icon"
    />

<View
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:layout_insetEdge="bottom"
    app:layout_behavior="android.support.design.widget.BottomSheetBehavior"
    />

并在onCreateView中加载相同的数据或调用相同的Web服务,如下所示:

 private boolean loadData = false;

 @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (this.isVisible() && isVisibleToUser ) {
            loadData = true;
            // Load your data or call web services 
            performDataRequestAsyncTask();
        }
    }

在初始化查看器页面的YourMainFragment中,添加此方法以获取currentTab

     if(!loadData && YourMainFragment.yourMainFragment.getCurrentTab() == CURRENT_TAB_INDEX){
           // Load your data or call web services 
        performDataRequestAsyncTask();
      }

答案 4 :(得分:0)

我使用Loader并初始化onPageSelected中每个片段的加载器。

答案 5 :(得分:0)

  

有源代码

   /**
 * Set the number of pages that should be retained to either side of the
 * current page in the view hierarchy in an idle state. Pages beyond this
 * limit will be recreated from the adapter when needed.
 *
 * <p>This is offered as an optimization. If you know in advance the number
 * of pages you will need to support or have lazy-loading mechanisms in place
 * on your pages, tweaking this setting can have benefits in perceived smoothness
 * of paging animations and interaction. If you have a small number of pages (3-4)
 * that you can keep active all at once, less time will be spent in layout for
 * newly created view subtrees as the user pages back and forth.</p>
 *
 * <p>You should keep this limit low, especially if your pages have complex layouts.
 * This setting defaults to 1.</p>
 *
 * @param limit How many pages will be kept offscreen in an idle state.
 */
public void setOffscreenPageLimit(int limit) {
    if (limit < DEFAULT_OFFSCREEN_PAGES) {//DEFAULT_OFFSCREEN_PAGES = 1
        Log.w(TAG, "Requested offscreen page limit " + limit + " too small; defaulting to " +
                DEFAULT_OFFSCREEN_PAGES);
        limit = DEFAULT_OFFSCREEN_PAGES;
    }
    if (limit != mOffscreenPageLimit) {
        mOffscreenPageLimit = limit;
        populate();
    }
}
  

您可以通过复制viewpager的源来自定义您的viewpager,然后更改此方法

像这样

public class LazyViewPager extends ViewGroup {
private static final String TAG = "LazyViewPager";
private static final boolean DEBUG = false;

private static final boolean USE_CACHE = false;

private static final int DEFAULT_OFFSCREEN_PAGES = 0;//change default to load one page,no offset,ViewPager is 1,so cache 2 Fragment
private static final int MAX_SETTLE_DURATION = 600; // ms

答案 6 :(得分:0)

我知道这是非常晚的答案但是出于上帝的缘故,你不必按照某人的建议编写自己的观看者。

让我们从头开始:

viewpager的工作原理:

默认情况下,它会将一个项目保留在内存中的任何一侧,这样就不必每次都创建它。

第一个解决方案:

mViewPager.setOffscreenPageLimit(0);

导致:

  

请求的屏幕外页面限制0太小;默认为1

第二个解决方案:

您希望在片段实际对用户可见时更新片段,因此请使用以下方法:

@Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
           //Do something like 
           //adapter.notifyDataSetChanged();
        }
    }

希望将来帮助某人!!!

答案 7 :(得分:0)

在片段中添加此方法

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // load data here      resumePlayer(); 
    }else{
       // fragment is no longer visible    pausePlayer();
    }
}