【问题标题】:How to read dimension values from custom attribute?如何从自定义属性中读取维度值?
【发布时间】:2021-02-04 13:48:48
【问题描述】:

我有完全由我自己的 xml 组成的自定义按钮。我可以为它设置样式、颜色和文本+图标,但现在我需要设置自定义文本大小。

我在我的样式属性中添加了新属性<attr name="l_buttonTextSize" format="dimension"/>,然后我从维度app:l_buttonTextSize="@dimen/text_small" 中设置了textSize 的值。但是我在按钮初始化时看不到它。

这就是我读取该值的方式:

val buttonTxtSize = typedArray.getFloat(btnTextSizeIndex, resources.getDimension(R.dimen.text_medium))
setButtonTextSize(buttonTxtSize)

fun setButtonTextSize(value: Float){
    buttonText.setTextSize(TypedValue.COMPLEX_UNIT_PX, value)
}

我有这个例外:

java.lang.NumberFormatException: For input string: "12.0sp"

看起来像发送字符串而不是维度值作为浮点数。

【问题讨论】:

  • getDimension 而不是getFloat?

标签: android android-layout android-attributes


【解决方案1】:

您可以使用getDimensionPixelSize

val buttonTxtSize = typedArray.getDimensionPixelSize(btnTextSizeIndex, resources.getDimension(R.dimen.text_medium))

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-10
    相关资源
    最近更新 更多