androidtranslate-animation

Are the numerical parameters of TranslateAnimation in dp or px?


I was reading through the documentation of TranslateAnimation and I saw that this is one of the many constructors of the TranslateAnimation class:

public TranslateAnimation (float fromXDelta, 
            float toXDelta, 
            float fromYDelta, 
            float toYDelta)

Reading further on what each of the parameters denote, I saw that fromXDelta means:

Change in X coordinate to apply at the start of the animation

[...and so on for the other parameters.]


Question:

I understand what these parameters imply but I do not know how to represent them. What's the metric and reference point? Are they meant to be in dp or pixels?


Solution

  • Like @Mike M. said, most dimensions on the code side are in Pixel.

    However, this is not a hindrance as you can still convert easily from dp to px and back. Here are two functions you can use to achieve this:


    dp to px:

    public float convertDpToPixel(float dp, Context context) {
        return dp * ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    }
    


    px to dp

    public float convertPixelsToDp(float px, Context context) {
        return px / ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    }
    


    PS:

    If you need your returned dp value in int rather than float, you can just pass the value inside Math.round().

    I hope this helps someone out there. Merry coding!