gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 13:39:56 27 4
gpt4 key购买 nike

我有一个扩展 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()
}
}

知道为什么吗?我基本上是在按钮中绘制进度指示器

最佳答案

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

要做到这一点,您还应该有一个构造函数,它仅以 ContextAttributeSet 作为参数。您可以通过 R.attr.materialButtonStyle 作为 defStyleAttr 调用您的方法。

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

关于android - 扩展 MaterialButton 时,我无法检索在 styles.xml 中设置的自定义属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54601248/

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