动画imageView从屏幕的一侧到另一侧 - 安卓

时间:2015-09-26 16:45:52

标签: android animation translate-animation

我正在尝试使用ImageViewTranslateAnimation从当前位置(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. 

这不起作用,飞镖就消失了。我该怎么办?

1 个答案:

答案 0 :(得分:0)

使动画的变量成为一个类变量(以确保它不会很快被垃圾收集)。为了使ImageView在离开屏幕之前停止移动,您需要一个额外的类变量

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会一直运行,直到它到达模拟器窗口egde。因此它消失在右侧的硬件控制区域之下。为了让它早点停止,我用

进行了测试
    Rect myRect = new Rect();
    dart.getWindowVisibleDisplayFrame(myRect);
    sizex = myRect.width() * 0.9f;
    sizey = myRect.height();
几乎完成了这个伎俩。它只是一个近似,好吧,但是获得显示器的确切尺寸 - 考虑填充或插入 - 似乎很难。至少低于API 20。

希望这无论如何都有帮助:)

相关问题