将 imageView 从屏幕的一侧动画化到另一侧 - android

Animate imageView from one side of screen to the other - android

我正在尝试使用 TranslateAnimationImageView 从当前位置 (0,Yscreensize/2) 到屏幕的另一侧 (Xscreensize,imageview.getY()) 制作动画,但我无法管理它上班。这是我的代码:

    dart = (ImageView) findViewById(R.id.dart);
    Display disp = getWindowManager().getDefaultDisplay();
    Point poi = new Point();
    disp.getSize(poi);
    sizex = poi.x;
    sizey = poi.y;
    ViewTreeObserver vto = dart.getViewTreeObserver();
    vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
        public boolean onPreDraw() {
            dart.getViewTreeObserver().removeOnPreDrawListener(this);
            finalHeight = dart.getMeasuredHeight();
            dart.setY(sizey / 2 - finalHeight);
            return true;
        }
    }); // till now - got screen size and set dart imageview to Y middle.

现在,当我尝试使用动画时:

 TranslateAnimation animation = new TranslateAnimation(dart.getX(), sizex, dart.getY(), dart.getY());
 animation.setDuration(10000);
 dart.startAnimation(animation); // from current x to screen size, from currenty to currenty. 

这是行不通的,飞镖会消失。我能做什么?

将动画变量设为 class 变量(以确保它不会很快被垃圾回收)。为了让ImageView在离开屏幕之前停止移动,你需要一个额外的class变量

float finalWidth;

然后像这样更改您的 OnPreDrawListener

vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener()
{
    public boolean onPreDraw()
    {
        dart.getViewTreeObserver().removeOnPreDrawListener(this);
        float finalHeight = dart.getMeasuredHeight();

        // if you want the view to stop before it leaves the screen
        float finalWidth = dart.getMeasuredWidth();

        animation = new TranslateAnimation(0, sizex - finalWidth, 0, 0);
        animation.setDuration(10000);

        // use this if you want the changes to persist
        // animation.setFillAfter(true);

        dart.setY(sizey / 2 - finalHeight);
        return true;
    }
}); 

我用一个按钮来呼叫 'startAnimation()'。使用模拟器进行测试时的唯一问题是 ImageView 保持 运行 直到它到达模拟器 window egde。因此它消失在右侧的硬件控制区域下方。为了让它早点停止,我测试了

    Rect myRect = new Rect();
    dart.getWindowVisibleDisplayFrame(myRect);
    sizex = myRect.width() * 0.9f;
    sizey = myRect.height();

几乎成功了。好吧,这只是一个近似值,但要获得显示的确切尺寸(考虑填充或插入)似乎很困难。至少低于API 20.

希望这有帮助:)