Search code examples
androidandroid-layoutlayoutdpi

how can I set ImageView position in dpi fro android api 8?


my android app supports Android api 8

and I want to move an object x dpi to the left.

how can I do it?


Solution

  • You should transform the amount of dip to the right amount of pixels for the given screen.

    This is the formula you should use:

    pixels = dip * (density / 160)
    

    the (density / 160) part is known as the density scale factor. You can get this scale factor using the following code.

    float scale = getContext().getResources().getDisplayMetrics().density;
    

    Than calculate the right amount of pixels from the given amount of dip and round it:

    int pixels (int) (dip * scale + 0.5f);
    

    In function form it would look like this.

    public int getPixelFromDip(float dip){
        final float scale = getContext().getResources().getDisplayMetrics().density;
        return (int) (dip * scale + 0.5f);
    }
    

    Rolf