19

I have two szenarios:

First:

 textView.setTextSize(getResources().getDimension(R.dimen.defaultTextSize));

Second in xml:

android:textSize="@dimen/defaultTextSize"

in values/dimen.xml i have declared defaultTextSize with 20sp

In my first case the text is much bigger (and different in some screenresulutions) than in my second case. Why? Have I done a mistake?

Ef Ge
  • 788
  • 1
  • 9
  • 26

5 Answers5

27

setTextSize() takes unit as pixel

Use this

public float pixelsToSp(float px) 
{
    float scaledDensity = _context.getResources().getDisplayMetrics().scaledDensity;
    return px/scaledDensity;
}

textView.setTextSize(pixelsToSp(getResources().getDimension(R.dimen.defaultTextSize)));

or

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.defaultTextSize))
Rohit5k2
  • 17,948
  • 8
  • 45
  • 57
  • 2
    Absolutely no clue why, but the second recommendation does not work on my GalaxyS4. Oi Vey Android...but solution 1 worked, so thanks. – Chris Sprague May 07 '15 at 02:02
  • 3
    @Kufuma it doesn't work because it's wrong: should be `COMPLEX_UNIT_PX` instead of `COMPLEX_UNIT_SP`. See also Blackbelt's answer in this page. – Giulio Piancastelli Nov 27 '15 at 10:40
16

The implementation of setTextSize(float size)

public void setTextSize(float size) {
    setTextSize(TypedValue.COMPLEX_UNIT_SP, size);
}

What is happening, in your case, is that you are scaling the value you provided to setTextSize, since getDimension returns the dimension multiplied by the metric. Try with

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.defaultTextSize));
Blackbelt
  • 156,034
  • 29
  • 297
  • 305
2

Add the size in dimens.xml

   <dimen name="text_medium">18sp</dimen>

Then, use the following to set the size wherever you want

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimension(R.dimen.text_medium));
Sonu Sourav
  • 2,926
  • 2
  • 12
  • 25
1

Have you tried using

   textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,getResources().getDimension(R.dimen.defaultTextSize));
Braunster
  • 466
  • 4
  • 6
0

TextView uses Resources.getDimensionPixelSize method, not Resources.getDimension for textSize.

Volodymyr Baydalka
  • 3,635
  • 1
  • 12
  • 13