Home » Android » android – Relative translation in property animation in xml

android – Relative translation in property animation in xml

Posted by: admin June 15, 2020 Leave a comment

Questions:

Currently I have an ImageView that extends the length of the device and is scaled by 3. Obviously, the sides are cropped outside the screen. I want the animation to start with the left-side of the image on the left-side of the device, then shift it over until the right-side of the image is on the right side of the device.

I can achieve them by setting up the image to it’s initial base then basically doing this:

  <objectAnimator
    android:propertyName="translationX"
    android:duration="6000"
    android:valueTo="-1280"
    android:valueType="floatType"
  />

However, this only works because I know the exact size of the image and the exact size of my Motorola Xoom. Naturally, I want this to work on any device, so I need something less hard-coded. With Tween animations, it works alright since you can translate something based off a percentage of it’s size. It wasn’t perfect, but it worked well enough for this effect. Property aniimations don’t seem to have this. The translationX and the X properties must have units.

Is there a simple way to translate a view with property animations based on the relative location? Am I going to have to make a separate animation file for each dimension? Is there any other way I can achieve this effect? I’d prefer not to make my own animation.

How to&Answers:

Could you create code for separate device size ‘buckets’ that you want to support (e.g. tablet, phone landscape etc.) which has known dp widths. Then you could use this could below to scale the image (where 384 is 384dp for a certain device bucket width) and do something similar for the the valueTo int you need.

//Get the device screen pixel density so that you can scale
//the image in density independent pixels rather than pixels
final float scale = getActivity().getResources().
getDisplayMetrics().density;

//set the number of dp for the height and width by changing
//the number you multiply the (scale + 0.5f) by e.g. 384
int pixelsh = (int) (384 * scale + 0.5f);
int pixelsw = (int) (384 * scale + 0.5f);

This is the way to convert absolute pixels to dp pixels. I do not know how to use these for what you are doing but at least it is a start.

Answer:

You should create the animation at run time by passing the screen size of the current device screen. First get the screen size (NOTE: the metrics (width, height) change depending on the rotation of the device):

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

int screenSize = metrics.widthPixels;

and then create your ObjectAnimator:

ObjectAnimator oa = ObjectAnimator.ofFloat(*yourImageView*, "translationX", 0, (Float) screenSize);
oa.setDuration(6000);
oa.start();