2015-10-01 58 views
-1

我试图在不同的视图上实现一组动画,这些视图是启动画面的组件。Android动画:将视图设置为父布局的中心

我已阅读开发人员网站上的属性动画,但我无法弄清楚如何将视图(翻译+缩放)设置为父布局的中心。如果我将值50%或50%p传递给valueFrom属性,它会崩溃并说它是无效值。

我该如何做到这一点?我目前的动画师xml如下。

<?xml version="1.0" encoding="utf-8"?> 
<set xmlns:android="http://schemas.android.com/apk/res/android"> 
<set> 
    <objectAnimator 
     android:duration="1000" 
     android:propertyName="x" 
     android:valueFrom="50%" 
     android:valueTo="50%" /> 
    <objectAnimator 
     android:duration="1000" 
     android:propertyName="y" 
     android:valueFrom="0" 
     android:valueTo="50%" /> 
</set> 

+0

请投票的人请详细说明或建议对上述问题进行编辑? – Rohan

回答

1

您可以在代码中做到这一点编程:

下面的代码动画化从左上角到屏幕的中心视图。

// Run on UI thread so that the height and widths are set 
    Runnable r = new Runnable() { 

     @Override 
     public void run() { 
      // Assign the animation which makes it drop down into view 
      View view = yourParentView.findViewById(R.id.view); 
      View yourParentView = findViewById(R.id.parent); 
      int parentHeight = yourParentView.getHeight(); 
      int parentWidth = yourParentView.getWidth(); 
      int viewHeight = view.getHeight(); 
      int viewWidth = view.getWidth(); 

      Animation animation = getAnimation((parentHeight/2) - (viewHeight/2), (parentWidth/2) - (viewWidth/2)); 
      view.startAnimation(animation); 
     } 

    }; 
    new Handler(Looper.getMainLooper()).post(r); 

private static AnimationSet getAnimation(int x, int y) { 

    AnimationSet animSet = new AnimationSet(false); 
    animSet.addAnimation(new TranslateAnimation(0, 0, x, y)); 
    animSet.setDuration(DURATION); 
    return animSet; 
} 
+0

嗨@Rob。我正在尝试使用属性动画来实现此目的。另外我想保留xml中的动画(尽可能) – Rohan

+0

@Rohan检查我的编辑,看看这是否有用,如果是的话,我会修改我的答案,删除第一位。 – RobVoisey

+0

感谢您的快速响应。 xml位也没有工作。 – Rohan