RecyclerView实现设置最大高度maxHeight

RecyclerView是没有maxHeight属性配置的,但我们可以通过继承RecyclerView自定义实现此属性功能。

具体实现如下:

public class MaxHeightRecyclerView extends RecyclerView {
    private int mMaxHeight;

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

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

    public MaxHeightRecyclerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initialize(context, attrs);
    }

    private void initialize(Context context, AttributeSet attrs) {
        TypedArray arr = context.obtainStyledAttributes(attrs, R.styleable.MaxHeightRecyclerView);
        mMaxHeight = arr.getLayoutDimension(R.styleable.MaxHeightRecyclerView_maxHeight, mMaxHeight);
        arr.recycle();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        if (mMaxHeight > 0) {
            heightMeasureSpec = MeasureSpec.makeMeasureSpec(mMaxHeight, MeasureSpec.AT_MOST);
        }
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

在style.xml文件中加入:

<declare-styleable name="MaxHeightRecyclerView">
    <attr name="maxHeight" format="dimension" />
</declare-styleable>

然后就可以在xml中使用:

app:maxHeight="400dp"
上一篇 Android架构之MVC、MVP、MVVM
下一篇 Android中WebView加载页面出现白屏解决方案
目录
文章列表
1 Swift - class与staitc关键字的区别与使用(类方法、静态方法)
Swift - class与staitc关键字的区别与使用(类方法、静态方法)
2
FileZilla登录FTP报错220 (vsFTPd 3.0.2)-AUTH TLS
FileZilla登录FTP报错220 (vsFTPd 3.0.2)-AUTH TLS
3
微信小程序异步与同步获取本地缓存及其调用注意
微信小程序异步与同步获取本地缓存及其调用注意
4
Kubernetes执行滚动更新
Kubernetes执行滚动更新
5
OpenLDAP + phpLDAPadmin
OpenLDAP + phpLDAPadmin
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。