Android ViewPager与RecyclerViews落后

时间:2018-09-26 12:00:23

标签: android performance android-fragments android-viewpager

我的viewpager包含3个片段,在这些片段中没有imageview而是只有简单的单元格。当我切换到更长的片段(recyclerview有更多项目)时,viewpager落后了。

我录制视频以更好地理解:https://youtu.be/6IMzItswBGo

还有我的自定义viewpager,用于调整页面高度。

public class CustomPager extends ViewPager
{
    private int width = 0;
    public CustomPager(Context context) {
        super(context);
    }

    public CustomPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        int height = 0;
        width = widthMeasureSpec;
        if (getChildCount() > getCurrentItem()) {
            View child = getChildAt(getCurrentItem());
            child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            int h = child.getMeasuredHeight();
            if(h > height) height = h;
        }

        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public void onRefresh()
    {
        try {
            int height = 0;
            if (getChildCount() > getCurrentItem()) {
                View child = getChildAt(getCurrentItem());
                child.measure(width, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                int h = child.getMeasuredHeight();
                if(h > height) height = h;
            }

            int heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
            ViewGroup.LayoutParams layoutParams = this.getLayoutParams();
            layoutParams.height = heightMeasureSpec;
            this.setLayoutParams(layoutParams);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

我正在使用Dynamic height viewpager

2 个答案:

答案 0 :(得分:0)

在设置viewpager适配器时,使用此代码预加载所有3个片段。

 viewPager.setOffScreenPageLimit(3);

答案 1 :(得分:0)

onMeasure()方法中似乎花费了太多时间。我想知道为什么要将viewPage的高度更改为其子代的高度?