Domanda

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

È stato utile?

Soluzione

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

Altri suggerimenti

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;

}

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top