详解Android Material Design自定义动画的编写

2019-12-10 18:30:06于海丽

// get the element that receives the click event
final View imgContainerView = findViewById(R.id.img_container);

// get the common element for the transition in this activity
final View androidRobotView = findViewById(R.id.image_small);

// define a click listener
imgContainerView.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View view) {
    Intent intent = new Intent(this, Activity2.class);
    // create the transition animation - the images in the layouts
    // of both activities are defined with android:transitionName="robot"
    ActivityOptions options = ActivityOptions
      .makeSceneTransitionAnimation(this, androidRobotView, "robot");
    // start the new activity
    startActivity(intent, options.toBundle());
  }
});

在代码中可以用View.setTransitionName()来设置过渡动画
当你要关闭第二个Activity时,要反转过渡动画,那么可以调用Activity.finishAfterTransition()方法,而不是Activity.finish()。
Start an activity with multiple shared elements  用多共享元素启动Activity
若两个Activity拥有不只一个的共享元素,要在它们之间开始场景transition动画,在它们的layout中都要使用 android:transitionName (或在Activity中代码中调用View.setTransitionName() )来定义,并创建一个如下的 ActivityOptions 对象:

ActivityOptions options = ActivityOptions.makeSceneTransitionAnimation(this,
    Pair.create(view1, "agreedName1"),
    Pair.create(view2, "agreedName2"));

Use Curved Motion 使用曲线运动
在Material设计中的动画,依赖于曲线的时间插入值和空间运动模式。在android5.0(api21)及以上,可以自定义动画时间曲线和曲线运动模式。

PathInterpolator类是一个新的基于贝塞尔曲线或路径对象的插入器。这个插入器指定了一个1 x1正方形运动曲线,它使用(0,0)为锚点,(1,1)为控制点,作为构造函数的参数。你也可以定义一个path interpolator的xml资源: