1

I have a custom view that I need to pass a sp value from xml (styleable). What I tried:

styleable.xml:

<declare-styleable name="TagView">
    <attr name="tagText" format="string"/>
    <attr name="tagTextSize" format="dimension"/>
    <attr name="tagTextColor" format="color" />
</declare-styleable>

Where I get this attr:

private fun setAttrs(context: Context?, attrs: AttributeSet?) {

        val typedArray = context?.obtainStyledAttributes(attrs, R.styleable.TagView, 0, 0)

        if(typedArray!=null) {
            val tagText = typedArray.getString(R.styleable.TagView_tagText)
            val tagSize = typedArray.getDimensionPixelSize(R.styleable.TagView_tagTextSize, 0)
            val tagTextColor = typedArray.getColor(R.styleable.TagView_tagTextColor, Color.WHITE)

            if(tagText != null) {
                nameTextView?.text = tagText
            }

            if(tagSize != 0 ) {
                nameTextView?.textSize = tagSize.toFloat()
            }

            nameTextView?.setTextColor(tagTextColor)
        }
        typedArray?.recycle()
    }

But it don't get excalty the sp value (in density related)... Eg: if I set 15sp it won't be 15sp, but a VERY big size and a size that are not density independet.

I tried typedArray.getDimension(R.styleable.TagView_tagTextSize, 0f) but with the same result...

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
felipe.rce
  • 237
  • 2
  • 8
  • 35

1 Answers1

4

Try the following instead:

tagSize = a.getDimensionPixelSize(R.styleable.TagView_tagTextSize, 0);

if (tagSize > 0) {
    nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, tagSize );
}

Reference

Khemraj Sharma
  • 57,232
  • 27
  • 203
  • 212