77
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 ?

2 Answers 2

210

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))
4
  • 1
    why not to use getResources().getDimensionPixelSize() ?
    – Nizzy
    Aug 6, 2014 at 0:32
  • 1
    @Nizzy It's actually same. The difference is the return type. Since the second paramater of setTextSize() requires float value, getDimension() is a good choice.
    – Glenn
    Aug 6, 2014 at 1:14
  • What about padding?
    – sachithkn
    May 26, 2017 at 8:39
  • 1
    @sachithkn The 4 parameters of setPadding() (start, top, end, bottom) requires values as pixels too. getDimension() returned as pixel value. For example, I have 4dp resource with name small_margin, when I call getDimension(R.dimen.small_margin) it will return the product of 4dp and density of device (4dp * density). Let's say the device is Nexus 5, its density is xxhdpi, scaling factor of xxhdpi is 3, so the method will return 4dp * 3.0.
    – Glenn
    May 26, 2017 at 11:36
12

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()));
1
  • I don't understand your answer. I think getDimension returns a pixel value not SP value, as also mentioned in the accepted answer Jul 27, 2023 at 21:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.