how to scale font size for different screen size in android?

Scale font size for different support device

Different screen density using the following size scale:
  • xxxhdpi: 4.0
  • xxhdpi: 3.0
  • xhdpi: 2.0
  • hdpi: 1.5
  • mdpi: 1.0 (baseline)
  • ldpi: 0.75
A set of six generalized densities:
  • ldpi (low) ~120dpi
  • mdpi (medium) ~160dpi
  • hdpi (high) ~240dpi
  • xhdpi (extra-high) ~320dpi
  • xxhdpi (extra-extra-high) ~480dpi
  • xxxhdpi (extra-extra-extra-high) ~640dpi
Below function use for convert dp(Density indipendent pixel) to PX.
public static int dp2px(Context context, float dpValue) {
       final float scale = context.getResources().getDisplayMetrics().density;
       return (int) (dpValue * scale + 0.5f);
} 

Now We are going to set dynamic font size for all device 
Note: It will work only on the device, not on the tablet. we need to write different logic for the tablet.
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,dp2px(this,12f));

How It works on different screen.

  • xxxhdpi: 4.0 =(12*4.0+0.5) =48.5
  • xxhdpi: 3.0 =(12*3.0+0.5) =36.5
  • xhdpi: 2.0 =(12*2.0+0.5) =24.5
  • hdpi: 1.5 =(12*1.5+0.5) =18.5
  • mdpi: 1.0 (baseline) =(12*1.0+0.5) =12.5
  • ldpi: 0.75 =(12*0.75+0.5) =9.5
Reference links
http://developer.android.com/training/multiscreen/screendensities.html
http://developer.android.com/guide/practices/screens_support.html



Comments

Popular posts from this blog

Android studio short cuts lists

Android status bar and navigation bar height