利用自定义xml属性指定来RecyclerView的LayoutManager

最近在学习使用RecyclerView时希望根据所inflate的XML文件的来动态的指定LayoutManager,通常的做法是通过自定义属性的方法来指定LayoutManager,但是经过研究源码发现预设的几种LayoutManager都提供了一个构造器,适用于当在布局文件中自定义了LayoutManager时指定。以StaggeredGridLayoutManager的构造器为例
    /**
     * Constructor used when layout manager is set in XML by RecyclerView attribute
     * "layoutManager". Defaults to single column and vertical.
     */
    @SuppressWarnings("unused")
    public StaggeredGridLayoutManager(Context context, AttributeSet attrs, int defStyleAttr,
            int defStyleRes) {
        Properties properties = getProperties(context, attrs, defStyleAttr, defStyleRes);
        setOrientation(properties.orientation);
        setSpanCount(properties.spanCount);
        setReverseLayout(properties.reverseLayout);
        setAutoMeasureEnabled(mGapStrategy != GAP_HANDLING_NONE);
        mLayoutState = new LayoutState();
        createOrientationHelpers();
    }

其他几种预设的LayoutManager的子类都有类似的构造器。

根据注释可以知道当XML指定了自定义属性layoutManager时,系统会根据该属性值来指定LayoutManager,据此只要在写布局文件时,添加自定义属性就可以直接指定LayoutManager。

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:recyclerView="http://schemas.android.com/apk/res-auto"
    android:id="@id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    recyclerView:layoutManager="StaggeredGridLayoutManager"
    recyclerView:spanCount="5"
    recyclerView:reverseLayout="false"
    recyclerView:stackFromEnd="false"
    >

</android.support.v7.widget.RecyclerView>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值