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