一熄守、前言:
在日常開發(fā)中,想直接通過android:maxHeight或android:maxWidth在布局文件中限制RecyclerView的最大高度寬度判耕,是無法實(shí)現(xiàn)的柑蛇。通過自定義RecyclerView,覆蓋onMeasure方法兆龙。在onMeasure方法內(nèi)部杖爽,當(dāng)發(fā)現(xiàn)自身高度或?qū)挾瘸^限制的最大高度或?qū)挾龋瑒t手動將寬或高設(shè)置為期望的最大寬或搞紫皇。具體代碼實(shí)現(xiàn)如下:
1慰安、自定義MaxLimitRecyclerView
/**
* max limit-able RecyclerView
*/
public class MaxLimitRecyclerView extends RecyclerView {
private int mMaxHeight;
private int mMaxWidth;
public MaxLimitRecyclerView(Context context) {
this(context, null);
}
public MaxLimitRecyclerView(Context context, @Nullable AttributeSet attrs) {
this(context, attrs, 0);
}
public MaxLimitRecyclerView(Context context, @Nullable AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
inti(attrs);
}
private void inti(AttributeSet attrs) {
if (getContext() != null && attrs != null) {
TypedArray typedArray = null;
try {
typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.MaxLimitRecyclerView);
if (typedArray.hasValue(R.styleable.MaxLimitRecyclerView_limit_maxHeight)) {
mMaxHeight = typedArray.getDimensionPixelOffset(R.styleable.MaxLimitRecyclerView_limit_maxHeight, -1);
}
if (typedArray.hasValue(R.styleable.MaxLimitRecyclerView_limit_maxWidth)) {
mMaxWidth = typedArray.getDimensionPixelOffset(R.styleable.MaxLimitRecyclerView_limit_maxWidth, -1);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (typedArray != null) {
typedArray.recycle();
}
}
}
}
@Override
protected void onMeasure(int widthSpec, int heightSpec) {
super.onMeasure(widthSpec, heightSpec);
boolean needLimit = false;
if (mMaxHeight >= 0 || mMaxWidth >= 0) {
needLimit = true;
}
if (needLimit) {
int limitHeight = getMeasuredHeight();
int limitWith = getMeasuredWidth();
if (getMeasuredHeight() > mMaxHeight) {
limitHeight = mMaxHeight;
}
if (getMeasuredWidth() > mMaxWidth) {
limitWith = mMaxWidth;
}
setMeasuredDimension(limitWith, limitHeight);
}
}
}
2、對應(yīng)屬性xml
注意:在res下的values中創(chuàng)建attrs.xml,導(dǎo)入下面的代碼
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!--attribute for MaxLimitRecyclerView-->
<declare-styleable name="MaxLimitRecyclerView">
<attr name="limit_maxHeight" format="reference|dimension" />
<attr name="limit_maxWidth" format="reference|dimension" />
</declare-styleable>
</resources>
圖片.png
3聪铺、使用
<your_package_name.MaxLimitRecyclerView
android:id="@+id/act_choose_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:limit_maxHeight="@dimen/dp_255"
app:limit_maxWidth="@dimen/dp_275"
tools:itemCount="8" />
必須指定RecyclerView的最大值和最小值
app:limit_maxHeight="@dimen/dp_255"
app:limit_maxWidth="@dimen/dp_275"
以上化焕,便可實(shí)現(xiàn)對RecyclerView最大高度或?qū)挾鹊南拗啤?/p>