defStyleAttrs参数如何在obtainStyledAttributes中使用

时间:2013-12-23 17:21:14

标签: android android-custom-view

我正在尝试在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参数,请告诉我。如果有人知道,为什么需要同时使用defStyleAttrdefStyleRes参数似乎只需defStyleRes即可?

1 个答案:

答案 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" >