如何指定通过RecyclerView的“layourManager”属性分配的LayoutManager的属性?

问题描述:

根据Google的RecyclerView documentation,您可以在布局文件中通过在RecyclerView的'layoutManager'属性中指定其类名来设置特定的LayoutManager。它还特别提到LayoutManager有一个构造函数,它接受AttributeSet如何指定通过RecyclerView的“layourManager”属性分配的LayoutManager的属性?

我的问题是因为你通过RecyclerView的元素属性指定了LayoutManager,而不是它自己的元素,在那里/如何设置针对LayoutManager本身的属性?

我的猜测是你直接将它们添加到RecyclerView元素。这在RecyclerView的构造函数中是有意义的,当它在'layoutManager'属性中指定LayoutManager时,它可以简单地通过传递给它的相同AttributeSet。但是,这只是一个猜测。

这里是我思考什么是正确的方法的例子:

<MyRecyclerView 
    app:layoutManager=".MyLayoutManager" 
    app:attrOnlyUsedByRecyclerView="I'm used by MyRecyclerView" 
    app:attrOnlyUsedByLayoutManager="I'm used by MyLayoutManager" /> 

注意三个属性是如何在技术上设置MyRecyclerView元素,但思路是第三属性是忽略,从MyRecyclerView的构造函数传入MyLayoutManager的构造函数。

我试图构建一个演示应用程序来测试现在的理论,但在此期间,任何人都可以澄清肯定,或者至少指出我在正确的方向,如果这是不正确的?

基于一点测试,似乎您可以将相关属性直接应用到RecyclerView元素,并且它们将传递到LayoutManager

例如,对于LinearLayoutManager相关的构造函数是:

/** 
* Constructor used when layout manager is set in XML by RecyclerView attribute 
* "layoutManager". Defaults to vertical orientation. 
* 
* @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_android_orientation 
* @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_reverseLayout 
* @attr ref android.support.v7.recyclerview.R.styleable#RecyclerView_stackFromEnd 
*/ 
public LinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, 
          int defStyleRes) { 
    Properties properties = getProperties(context, attrs, defStyleAttr, defStyleRes); 
    setOrientation(properties.orientation); 
    setReverseLayout(properties.reverseLayout); 
    setStackFromEnd(properties.stackFromEnd); 
    setAutoMeasureEnabled(true); 
} 

...这里是你如何指定LayoutManager的 'stackFromEnd' 属性。 (注意它是如何设置它,即使它注定了LayoutManagerRecyclerView元素。)

<android.support.v7.widget.RecyclerView 
    android:id="@+id/recycler_view" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="horizontal" 
    app:layoutManager="android.support.v7.widget.LinearLayoutManager" 
    app:stackFromEnd="true" /> 
+0

完美!我只是澄清了你的文字,以便特别指出要点,并将你的标记标记为已接受。谢谢!如果您觉得它为网站增添价值,请务必将此问题也投票给您。 – MarqueIV