Setting textSize programmatically

Android

Android Problem Overview


textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, getResources().getDimension(R.dimen.result_font));

The following code works, but the R.dimen.result_font is taken as a much bigger value than it really is. Its maybe about 18sp-22sp or 24sp according to the screen size ... But the size set here is at least about 50sp. Can someone please recommend something ?

Android Solutions


Solution 1 - Android

You have to change it to TypedValue.COMPLEX_UNIT_PX because getDimension(id) returns a dimen value from resources and implicitly converted to px.

Java:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 
                     getResources().getDimension(R.dimen.result_font));

Kotlin:

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 
                     resources.getDimension(R.dimen.result_font))

Solution 2 - Android

Requirement

Suppose we want to set textView Size programmatically from a resource file.

Dimension resource file (res/values/dimens.xml)

<resources>     
   <dimen name="result_font">16sp</dimen>
</resources>

Solution

First get dimen value from resource file into a variable "textSizeInSp".

int textSizeInSp = (int) getResources().getDimension(R.dimen.result_font);

Next convert 16 sp value into equal pixels.

for that create a method.

 public static float convertSpToPixels(float sp, Context context) {
    return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, context.getResources().getDisplayMetrics());
}

Let's set TextSize,

textView.setTextSize(convertSpToPixels(textSizeInSp , getApplicationContext()));

All together,

int textSizeInSp = (int) getResources().getDimension(R.dimen.result_font);
textView.setTextSize(convertSpToPixels(textSizeInSp , getApplicationContext()));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRakeeb RajbhandariView Question on Stackoverflow
Solution 1 - AndroidGlennView Answer on Stackoverflow
Solution 2 - AndroidJayakrishnanView Answer on Stackoverflow