Layout Animations主要使用LayoutTransition为布局的容器设置动画,当容器中的视图层次发生变化时存在过渡的动画效果。
LayoutTransition
This class enables automatic animations on layout changes in ViewGroup objects. To enable transitions for a layout , create a LayoutTransition object and set it on any ViewGroup by calling setLayoutTransition(LayoutTransition)
. This will cause default animations to run whenever items are added to or removed from that container. To specify custom animations, use the setAnimator() method.
setLayoutTransition(LayoutTransition)
在ViewGroup设置这个过度动画。我们也可以在视图的添加和删除时通过setAnimator()来设置动画。 我们来看一下LayoutTransition的使用:
1 LayoutTransition transition = new LayoutTransition();//创建LayoutTransition的对象。2 transition.setDuration(3000);//设置添加过度动画显示的时间。3 transition.setAnimator(LayoutTransition.APPEARING, AnimatorInflater.loadAnimator(this, R.animator.animator));//添加动画4 mGridLayout.setLayoutTransition(transition);//将LayoutTransition添加到ViewGroup容器中。
Layout Animations实例应用
我们在布局中添加一个按钮,通过点击按钮来实现在GridLayout布局中动画形式增加一个按钮,点击添加按钮,按钮会自动删除。
布局文件:17 8 13 18 19
Activity:
1 public class LayoutAnimatorActivity extends Activity { 2 private Button mButtonAdd; 3 private GridLayout mGridLayout; 4 private int count; 5 6 @Override 7 protected void onCreate(Bundle savedInstanceState) { 8 super.onCreate(savedInstanceState); 9 setContentView(R.layout.activity_layout_animator);10 mButtonAdd = (Button) findViewById(R.id.button);11 mGridLayout = (GridLayout) findViewById(R.id.gridlayout);12 13 //设置布局的动画14 LayoutTransition transition = new LayoutTransition();15 transition.setDuration(1000);16 transition.setAnimator(LayoutTransition.APPEARING, transition17 .getAnimator(LayoutTransition.APPEARING));18 transition.setAnimator(LayoutTransition.CHANGE_APPEARING, transition.getAnimator(LayoutTransition.CHANGE_APPEARING));19 transition.setAnimator(LayoutTransition.DISAPPEARING, transition.getAnimator(LayoutTransition.DISAPPEARING));20 transition.setAnimator(LayoutTransition.CHANGE_DISAPPEARING, transition.getAnimator(LayoutTransition.CHANGE_DISAPPEARING));21 mGridLayout.setLayoutTransition(transition);22 23 mButtonAdd.setOnClickListener(new View.OnClickListener() {24 @Override25 public void onClick(View v) {26 count++;27 final Button button = new Button(LayoutAnimatorActivity.this);28 ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);29 button.setLayoutParams(params);30 button.setText(""+count);31 button.setOnClickListener(new View.OnClickListener() {32 @Override33 public void onClick(View v) {34 mGridLayout.removeView(v);35 }36 });37 mGridLayout.addView(button);38 }39 });40 }41 }
这里使用到了LayoutTransition的四种效果:
APPEARING:当一个View在ViewGroup中出现时,对此View设置的动画
CHANGE_APPEARING:当一个View在ViewGroup中出现时,对此View对其他View位置造成影响,对其他View设置的动画。
DISAPPEARING: 当一个View在ViewGroup中消失时,对此View设置的动画。
CHANGE_DISAPPEARING: 当一个View在ViewGroup中消失时,对此View对其他View位置造成影响,对其他View设置的动画。
CHANGE: 不是由于View出现或消失造成对其他View位置造成影响,然后对其他View设置的动画。