设置RecyleView的最大高度

2020-01-15  本文已影响0人  sunny635533

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

<declare-styleable name="MaxHeightRecyclerView">

    <attr name="maxHeight" format="dimension" />

</declare-styleable>

2、 重写recycleView的onMeasure方法:

import android.content.Context;

import android.content.res.TypedArray;

import android.support.v7.widget.RecyclerView;

import android.util.AttributeSet;

/**

* 设置recycleView最大的高度

* 用法:

*<MaxHeightRecyclerView

*            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);

    }

}

上一篇 下一篇

猜你喜欢

热点阅读