Translate animation to correct position in Android

2019-07-19 11:20发布

问题:

I have created an animation for an image in my application. The image starts coming from the middle till the top left corner of screen. Now I need to make sure that the image get placed at the right position in all the devices which is at the top left corner. Currently it gets placed at different positions for different devices at the top left corner. How can I fix it ? I have my code as follows :

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator"
    android:fillAfter="true">
    <translate
        android:fromXDelta="0%p"
        android:toXDelta="-36%p"
        android:fromYDelta="0%p"
        android:toYDelta="-30.9%p"
        android:duration="500"
        android:fillAfter="true" />
</set>

Can anyone please help.

回答1:

I got some pretty good results with this, so hope this helps you or any one. The idea is simple.

Position what you want to animate to it's final position via xml then I use TranslateAnimation and set its from values to any float values and to values as 0. In this way the widget/view animates and comes to rest in the place where you have positioned it in xml.

A small example to animate a TextView from outside the screen to its position specified in xml.

//This is just for getting the from value, from where animation starts.
WindowManager wm = (WindowManager) mContext
        .getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int width = display.getWidth();

Animation  moveRighttoLeft = new TranslateAnimation(width, 0, 0, 0);
moveRighttoLeft.setDuration(700);

AnimationSet animation = new AnimationSet(false);
animation.addAnimation(moveRighttoLeft);
myTextView.setAnimation(animation);

Here are the xml's

<TextView
    android:id="@+id/mytextview"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="This is a Text View"
    android:layout_marginLeft="30dp"/>