我正在尝试在android上创建自定义复合视图(从relativelayout子类化)并尝试指定默认样式。我可以做到这一点,但我想知道defStyleAttr参数用于什么,以及如何使用它。
我遇到了这个方法context.obtainStyledAttributes(AttributeSet set,int [] attrs,int defStyleAttr,int defStyleRes)。
我理解:
AttributeSet set
我将从视图的构造函数中获取if
从XML膨胀,int[] attrs
将成为任何关键值
我可能已创建的自定义视图字段int defStyleRes
将是一个
我可以提供的默认样式,它被定义为样式
资源。但是,我无法弄清楚如何使用int defStyleAttr
参数。我已经阅读了文档并提供了这样的attr资源:
<declare-styleable name="BMTheme">
<attr name="BMButtonStyle" format="reference" />
</declare-styleable>
然后在我的主题资源文件中我有这个:
<style name="Theme.Custom" parent="@android:style/Theme">
<item name="BMButtonStyle">@style/BMButton</item>
</style>
反过来引用这种风格:
<style name="BMButton">
<item name="text">some string</item>
<item name="android:paddingLeft">10dp</item>
<item name="android:paddingRight">10dp</item>
</style>
在代码中,当我为defStyleAttr
传递0并为defStyleRes
传递样式资源ID时,我成功获取了我在BMButton样式中定义的默认值:
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.RightArrowButton, 0, R.style.BMButton);
然而,当我为defStyleAttr
传递BMButtonStyle的attr资源ID(进而引用BMButton样式),为defStyleRes
传递0时,我没有得到我在样式中指定的值。
TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.RightArrowButton, R.attr.BMButtonStyle, 0);
如果我以错误的方式使用defStyleAttr
参数,请告诉我。如果有人知道,为什么需要同时使用defStyleAttr
和defStyleRes
参数似乎只需defStyleRes
即可?
答案 0 :(得分:5)
我在读完这篇文章后想出了我的错误: Creating default style with custom attributes
基本上,为了使用defStyleAttr
参数,我的项目需要在清单中设置我的自定义主题定义主题。
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/Theme.Custom" >