gpt4 book ai didi

android - 如何为通过 RecyclerView 的 'layoutManager' 属性分配的 LayoutManager 指定属性?

转载 作者:行者123 更新时间:2023-11-30 00:18:24 26 4
gpt4 key购买 nike

根据谷歌的 RecyclerView documentation ,您可以通过在 RecyclerView 的“layoutManager”属性中指定其类名,从布局文件中设置特定的 LayoutManager。它还特别提到 LayoutManager 有一个接受 AttributeSet 的构造函数。

我的问题是,由于您是通过 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”属性。 (注意它是如何在 RecyclerView 元素上设置的,即使它是为 LayoutManager 指定的。)

<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" />

关于android - 如何为通过 RecyclerView 的 'layoutManager' 属性分配的 LayoutManager 指定属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46757499/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com