gpt4 book ai didi

android - 如何为自定义 RecyclerView.LayoutManager 实现的 LayoutParams 类定义自定义属性?

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

我知道如何为特定类创建自定义属性。您只需使用类名作为名称在 Styleable 中定义它们,就像这样。

<declare-styleable name="MyCustomView">
<attr name="customAttr1" format="integer" />
<attr name="customAttr2" format="boolean" />
</declare-styleable>

然后,当我在我的布局中使用 MyCustomView 实例时,customAttr1customAttr2 可用于设置。很简单。

我现在想做的是在我的自定义 RecyclerView 的子级上使用 LayoutParams 的自定义属性,或者更准确地说,在为我正在使用的各个 RecyclerView.ViewHolder 子类提供布局文件。但是,我无法获得传递给我的属性,我不确定为什么不这样做。

这是我的 attrs.xml 文件...

<?xml version="1.0" encoding="utf-8"?>
<resources>

<declare-styleable name="ScrollableGridLayoutManager.LayoutParams">
<attr name="cellLayoutMode">
<enum name="scrollable" value="0" />
<enum name="fixedHorizontal" value="1" />
<enum name="fixedVertical" value="2" />
<enum name="fixedHorizontalAndVertical" value="3" />
</attr>
</declare-styleable>

</resources>

这是读取属性的自定义 LayoutParams 类中的代码...

public LayoutParams(Context context, AttributeSet attrs){

super(context, attrs);

TypedArray styledAttrs = context.obtainStyledAttributes(R.styleable.ScrollableGridLayoutManager_LayoutParams);

if(styledAttrs.hasValue(R.styleable.ScrollableGridLayoutManager_LayoutParams_cellLayoutMode)){
int layoutModeOrdinal = styledAttrs.getInt(R.styleable.ScrollableGridLayoutManager_LayoutParams_cellLayoutMode, layoutMode.ordinal());
layoutMode = LayoutMode.values()[layoutModeOrdinal];
}

styledAttrs.recycle();
}

这里是我在布局中为我的一个 ViewHolders 设置它的地方...

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android = "http://schemas.android.com/apk/res/android"
xmlns:app = "http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="start|center_vertical"
android:background="#0000FF"
app:cellLayoutMode="fixedVertical">

<TextView
android:id="@+id/mainTextView"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FFFF00"
android:layout_marginStart="20dp" />

</LinearLayout>

但是,我尝试的任何东西似乎都没有进入“hasValue”调用。它总是像未设置一样返回。

注意:我在定义属性时也尝试了所有这些...

<declare-styleable name="LayoutParams">

<declare-styleable name="ScrollableGridLayoutManager_LayoutParams">

<declare-styleable name="ScrollableGridAdapter_LayoutParams">

...但似乎都不起作用。

那我做错了什么?您如何定义特定于自定义 LayoutParams 类的属性?

最佳答案

在自定义 LayoutParams 构造函数中,obtainStyledAttributes() 调用必须包含传入的 AttributeSet。否则,它只会从Context 的主题,以及布局 XML 中指定的那些属性值不会包含在返回的 TypedArray 中。

例如:

TypedArray styledAttrs =
context.obtainStyledAttributes(attrs, R.styleable.ScrollableGridLayoutManager_LayoutParams);

关于android - 如何为自定义 RecyclerView.LayoutManager 实现的 LayoutParams 类定义自定义属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46737466/

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