TypedValue.applyDimension producing wrong dimensions

337 Views Asked by At

I use TypedValue.applyDimension and displayMetrix.scaledDensity to set text size in the TextView on my Xiaomi Redmi 5 plus and get surprizing results: text in the TextView is much larger than the one (same sp value) set in layout attribute. Here's my layout:

<TextView
    android:id="@+id/my_text_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:gravity="center|start"
    android:layout_margin="4dp"
    android:text="Some Text"
    android:textSize="18sp" />

And here is how I change text size:

TextView titleView = itemView.findViewById(R.id.my_text_view);
titleView.setTextSize((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, 18, 
        getResources().getDisplayMetrics()));

I also tried to use formula as follows:

(int) getResources().getDisplayMetrics().scaledDensity * 18

On the emulator, I get the right text size, so I am not sure how to reproduce this. If someone manages to do that, please, leave comments for me and others to understand what is actually wrong. Thanks

1

There are 1 best solutions below

0
IchZerowan On

So, I opend TextView source code and found out that TextView.setTextSize accepts sp, not px. So the answer is not to convert sp to px, but to use sp by default, or, if you need to support several size units, use setTextSize(int unit, float size)