【问题标题】:Animate imageView from one side of screen to the other - android从屏幕的一侧到另一侧的动画图像视图 - android
【发布时间】:2015-09-28 14:51:48
【问题描述】:

我正在尝试使用 TranslateAnimation 从其当前位置 (0,Yscreensize/2) 到屏幕的另一侧 (Xscreensize,imageview.getY())ImageView 设置动画,但我无法使其正常工作。这是我的代码:

    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. 

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

【问题讨论】:

    标签: android animation translate-animation


    【解决方案1】:

    将动画的变量设为类变量(以确保它不会很快被垃圾收集)。为了让 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。

    希望这对你有帮助:)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-07
      • 2023-03-31
      • 1970-01-01
      • 2020-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多