扩展MaterialButton时无法检索在styles.xml中设置的自定义属性

时间:2019-02-08 22:43:36

标签: android material material-components-android

我有一个扩展MaterialButton的按钮,并且我正在尝试访问在styles.xml中定义的自定义属性。 但是TypedArray不包含它们

这是我的自定义样式

<style name="AppWidget.Button" parent="Widget.MaterialComponents.Button">
        <item name="android:padding">@dimen/textview_horizontal_padding</item>
        <item name="cornerRadius">24dp</item>
        <item name="android:insetTop">0dp</item>
        <item name="android:insetBottom">0dp</item>
        <item name="android:textAppearance">@style/AppStyle.TextAppearance.Button</item>
        <item name="android:textColor">@color/button_text</item>
        <item name="backgroundTint">@color/button_bg</item>
        <item name="strokeColor">@color/button_stroke</item>
        <item name="strokeWidth">2dp</item>
        <item name="progressWidth">20dp</item>
        <item name="progressColor">@color/dph_teal</item>
</style>

我的自定义属性是progressWidthprogressColor

这是我的attrs.xml

<declare-styleable name="Button">
        <attr name="progressColor" format="color" />
        <attr name="progressWidth" format="dimension" />
</declare-styleable>

我正在设置主题

<item name="materialButtonStyle">@style/AppWidget.Button</item>

以及我如何尝试检索它们

private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
        val ta = context.obtainStyledAttributes(attrs, R.styleable.Button, defStyleAttr, 0)
        try {
            val hasValue1 = ta.hasValue(R.styleable.Button_progressColor) //always false
            val hasValue2 = ta.hasValue(R.styleable.Button_progressWidth) //always false
            progressColor = ta.getColor(R.styleable.Button_progressColor, Color.WHITE)
            progressWidth = ta.getDimension(R.styleable.Button_progressWidth, 5f)
        } finally {
            ta.recycle()
        }
    }

知道为什么吗?我基本上是在按钮

中绘制进度指示器

2 个答案:

答案 0 :(得分:3)

为了读取以默认样式设置的值,您需要将正确的defStyleAttr传递给构造函数。

为此,您还应该有一个仅将ContextAttributeSet作为参数的构造函数。您可以通过将R.attr.materialButtonStyle作为defStyleAttr传递给您的方法。

obtainStyledAttributes的调用使用defStyleAttr的值来读取主题中设置的默认样式。

答案 1 :(得分:0)

我认为您可能忘记了在Androidmanifest.xml中设置样式,否则将无法加载

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppWidget.Button">