1

I use this code to set my text by one sp bigger but It increases the size too much...

public void doThis(MenuItem item){
        size = text.getTextSize();
        text.setTextSize(TypedValue.COMPLEX_UNIT_SP, (float) (size + 1));

    }

I want it to add only one sp...

thanks for help

Max
  • 319
  • 1
  • 4
  • 18

3 Answers3

1

Because you obtain your size in pixels and use it to translate to sp. First you need to convert size back to sp:

float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
float sizeNew = text.getTextSize() / scaledDensity; // obtain current size in sp
sizeNew += 1f; // add 1 sp
text.setTextSize(TypedValue.COMPLEX_UNIT_SP, sizeNew); // set new size in sp
Alex Salauyou
  • 14,185
  • 5
  • 45
  • 67
1

You are getting pixels instead of sp from getTextSize();

Try this:

text.setTextSize(TypedValue.COMPLEX_UNIT_SP, (text.getSize() / getResources().getDisplayMetrics().scaledDensity) + 1);
Dan Harms
  • 4,725
  • 2
  • 18
  • 28
0

You can use this function to change pixels to sp, you can see the whole thread here

public static float pixelsToSp(Context context, Float px) {
float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
return px/scaledDensity;

}

Community
  • 1
  • 1
César Cobo
  • 598
  • 5
  • 9