根据Fragment布局高度来自动适应的Viewpager

在最近的项目中,要用到ViewPager,但是viewpager是放在recycleview里面,高度是不确定的,只好重写measure方法来根据子布局的高度来动态生成viewpager的高度,但是有个缺点,就是不能根据子布局的高度来收缩viewpager的高度,为了这个优化,在网上找了一个多小时,终于找到个方法,下面直接贴使用的方法:

1.将自定义viewpager放进自己的项目

package com.plyou.leintegration.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;

import java.util.HashMap;
import java.util.LinkedHashMap;

/**
 * Created by admin on 2017/10/25.
 */

public class CustomViewPager extends ViewPager {

    private int current;
    private int height = 0;
    /**
     * 保存position与对于的View
     */
    private HashMap mChildrenViews = new LinkedHashMap();

    private boolean scrollble = true;

    public CustomViewPager(Context context) {
        super(context);
    }

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


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mChildrenViews.size() > current) {
            View child = mChildrenViews.get(current);
            if (child != null) {
                child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
                height = child.getMeasuredHeight();
            }
        }

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

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }

    public void resetHeight(int current) {
        this.current = current;
        if (mChildrenViews.size() > current) {

            LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) getLayoutParams();
            if (layoutParams == null) {
                layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, height);
            } else {
                layoutParams.height = height;
            }
            setLayoutParams(layoutParams);
        }
    }

    /**
     * 保存position与对于的View
     */
    public void setObjectForPosition(View view, int position) {
        mChildrenViews.put(position, view);
    }


    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        if (!scrollble) {
            return true;
        }
        return super.onTouchEvent(ev);
    }


    public boolean isScrollble() {
        return scrollble;
    }

    public void setScrollble(boolean scrollble) {
        this.scrollble = scrollble;
    }


}


2.在fragemnt的oncreatview里面调用viewpager方法

根据Fragment布局高度来自动适应的Viewpager_第1张图片


3.每次滑动viewpager重新设置高度


根据Fragment布局高度来自动适应的Viewpager_第2张图片

好了,大致完成,直接看下效果吧


你可能感兴趣的:(根据Fragment布局高度来自动适应的Viewpager)