我知道如何为特定类创建自定义属性。您只需使用名称的类名称在Styleable中定义它们,就像这样。
<declare-styleable name="MyCustomView">
<attr name="customAttr1" format="integer" />
<attr name="customAttr2" format="boolean" />
</declare-styleable>
然后,当我在布局中使用MyCustomView
的实例时,可以设置customAttr1
和customAttr2
。很容易。
我现在尝试做的是在我的自定义LayoutParams
的子项上使用RecyclerView
的自定义属性,或者更准确地说,在Feed的布局文件的根视图中使用自定义属性我正在使用的各个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&#39;呼叫。它总是会返回,就像它没有设置一样。
注意:我在定义属性时也尝试了所有这些...
<declare-styleable name="LayoutParams">
<declare-styleable name="ScrollableGridLayoutManager_LayoutParams">
<declare-styleable name="ScrollableGridAdapter_LayoutParams">
......但似乎都没有效果。
那么我做错了什么?如何定义特定于自定义LayoutParams
类的属性?
答案 0 :(得分:0)
在自定义LayoutParams
构造函数中,obtainStyledAttributes()
调用必须包含传入的AttributeSet
。否则,它只会从Context
的主题中提取值,而那些布局XML中指定的属性值不会包含在返回的TypedArray
。
例如:
TypedArray styledAttrs =
context.obtainStyledAttributes(attrs, R.styleable.ScrollableGridLayoutManager_LayoutParams);