美文网首页
Android 自定义最大宽度和高度的RecyclerView

Android 自定义最大宽度和高度的RecyclerView

作者: 一心729 | 来源:发表于2021-03-22 23:50 被阅读0次

原理就不再做说明了,相信了解自定义View的都可以看明白.
一. 代码部分

class AtMostRecyclerView : RecyclerView {

    private var maxHeight = LayoutParams.MATCH_PARENT
    private var maxWidth = LayoutParams.MATCH_PARENT


    constructor(context: Context) : this(context, null)

    constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet, 0)

    constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int) : super(
        context,
        attributeSet,
        defStyle
    ) {
        val a =
            context.obtainStyledAttributes(attributeSet, R.styleable.AtMostRecyclerView, defStyle, 0)
        maxHeight = a.getDimensionPixelSize(R.styleable.AtMostRecyclerView_maxHeight, maxHeight)
        maxWidth = a.getDimensionPixelSize(R.styleable.AtMostRecyclerView_maxWidth, maxWidth)
        a.recycle()
    }

    override fun onMeasure(widthSpec: Int, heightSpec: Int) {
        var tempWidthSpec = widthSpec
        if (maxWidth > 0) {
            tempWidthSpec = MeasureSpec.makeMeasureSpec(maxWidth, MeasureSpec.AT_MOST)
        }
        var tempHeightSpec = heightSpec
        if (maxHeight > 0) {
            tempHeightSpec = MeasureSpec.makeMeasureSpec(maxHeight, MeasureSpec.AT_MOST)
        }
        super.onMeasure(tempWidthSpec, tempHeightSpec)
    }
}

二.自定义属性

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="AtMostRecyclerView">
        <attr name="maxHeight" format="dimension" />
        <attr name="maxWidth" format="dimension" />
    </declare-styleable>
</resources>

三.xml中使用

<com.app.demo.widgets.AtMostRecyclerView
        android:id="@+id/amrv_content_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:maxHeight="120dp"
        app:maxWidth="220dp"/>

相关文章

网友评论

      本文标题:Android 自定义最大宽度和高度的RecyclerView

      本文链接:https://www.haomeiwen.com/subject/gtnthltx.html