سؤال

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

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

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

Try this:

text.setTextSize(TypedValue.COMPLEX_UNIT_SP, (text.getSize() / getResources().getDisplayMetrics().scaledDensity) + 1);

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;

}

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top