Reputation: 2295
I'm providing an option for text sizes and one of them is for the EditText
boxes. I've determined the original text size using EditText#getTextSize()
. The result is given in pixels. Once the user selects the text size, I use edittext.setTextSize(TypedValue.COMPLEX_UNIT_SP, chosen)
to apply the text size.
Problem is different screen sizes give me wildly different text sizes, e.g. on an ICS phone, EditText.getTextSize()
returns 36, which is absolutely massive and definitely not the default text size used throughout the system.
What am I doing wrong?
Upvotes: 0
Views: 2594
Reputation: 919
You are probably seeing different values due to different screen densities and the fact that the value you get from getTextSize() is in pixels(px). Density Independent Pixels(dp) and Scaled Pixels(sp) are adjusted to be independent of the screen density and they are what you should be using. To get dp or sp from px you can use a simple conversion like this:
public static float pxToDp( float px, Context context ) {
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float dp = px / ( metrics.densityDpi / 160f );
return dp;
}
or this (which I took from this post):
public static float pixelsToSp(Context context, Float px) {
float scaledDensity = context.getResources().getDisplayMetrics().scaledDensity;
return px/scaledDensity;
}
Upvotes: 2