LoginSignup
3
6

More than 5 years have passed since last update.

[Android] dp, px まわりの便利関数

Last updated at Posted at 2017-04-25
LayoutUtils.java
public abstract class LayoutUtils {

    public static int getDisplayWidthPx() {
        return Resources.getSystem().getDisplayMetrics().widthPixels;
    }

    public static int getDisplayHeightPx() {
        return Resources.getSystem().getDisplayMetrics().heightPixels;
    }

    public static int getDisplayWidthDp() {
        return px2dp(Resources.getSystem().getDisplayMetrics().widthPixels);
    }

    public static int getDisplayHeightDp() {
        return px2dp(Resources.getSystem().getDisplayMetrics().heightPixels);
    }

    public static int dp2px(int dp){
        return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
    }

    public static int px2dp(int px){
        return (int) (px / Resources.getSystem().getDisplayMetrics().density);
    }

    public static int getPxFromDimension(Context context, @DimenRes int resource) {
        return context.getResources().getDimensionPixelSize(resource);
    }

    public static int getDpFromDimension(Context context, @DimenRes int resource) {
        return px2dp(context.getResources().getDimensionPixelSize(resource));
    }
}
3
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
6