Sharj Sharj - 6 months ago 24
Android Question

View.setPadding accepts only in px, is there anyway to setPadding in dp?

Android

View.setPadding(int left, int top, int right, int bottom)
only accepts values in px but I want to set padding in dp. Is there any way around it?

Answer

Straight to code

    int padding_in_dp = 6;  // 6 dps
    final float scale = getResources().getDisplayMetrics().density;
    int padding_in_px = (int) (padding_in_dp * scale + 0.5f);