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

来源:互联网 发布:有域名了怎么建立网站 编辑:程序博客网 时间:2024/06/14 17:52
最近在学习使用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>

0 0