Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
112 views
in Technique[技术] by (71.8m points)

android - How to read dimension values from custom attribute?

I have custom Button which is completely made up by my own xml. I can set up style, color and text + icon to it, but now I need to set custom text size.

I added to my styleable attributes new attribute <attr name="l_buttonTextSize" format="dimension"/> then I set value for textSize from dimensions app:l_buttonTextSize="@dimen/text_small". But I cant read it in button initialization.

This is how I read that value:

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

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

I've got this exception:

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

Looks like string was send instead of dimension value as float.

question from:https://stackoverflow.com/questions/66046970/how-to-read-dimension-values-from-custom-attribute

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use getDimensionPixelSize

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...