设置RecyleView的最大高度

1、首先添加用样式,在attrs文件里添加如下代码:

   

2、 重写recycleView的onMeasure方法:

import android.content.Context;

import android.content.res.TypedArray;

import android.support.v7.widget.RecyclerView;

import android.util.AttributeSet;

/**

* 设置recycleView最大的高度

* 用法:

*

*            android:id="@+id/recycler_view"

*            android:layout_width="match_parent"

*            android:layout_height="wrap_content"

*            app:maxHeight="200dp" />

*/

public class MaxHeightRecyclerView extends RecyclerView {

    private int maxHeight;

    public MaxHeightRecyclerView(Context context) {

    super(context, null);    }

public MaxHeightRecyclerView(Context context, AttributeSet attributeSet) {

super(context, attributeSet);

        initialize(context, attributeSet);

    }

public MaxHeightRecyclerView(Context context, AttributeSet attributeSet, int defStyleAttr) {

super(context, attributeSet, defStyleAttr);

        initialize(context, attributeSet);

    }

public void initialize(Context context, AttributeSet attributeSet) {

if (attributeSet !=null) {

TypedArray typedArray = context.obtainStyledAttributes(attributeSet, R.styleable.MaxHeightRecyclerView);

            if (typedArray !=null) {

maxHeight = typedArray.getLayoutDimension(R.styleable.MaxHeightRecyclerView_maxHeight, maxHeight);

            }

}

}

@Override

    protected void onMeasure(int widthSpec, int heightSpec) {

if (maxHeight >0) {

heightSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST);

        }

super.onMeasure(widthSpec, heightSpec);

    }

}

你可能感兴趣的:(设置RecyleView的最大高度)