动画层

概念

        在Tween动画中,实际移动的只是组件的显示位置,因此组件响应点击事件的位置还是原来的地方,而不是经过移动后的地方。为了解决这个问题,可以使用属性动画,也可以新建一个动画层。

        动画层指的是:在原视图上新加盖一层ViewGroup,并在ViewGroup上新建要进行动画的视图,然后将新建的视图进行移动。当动画结束时,移除ViewGroup上所有的视图,同时更改原视图中的资源。

示例

	private ImageView iv1, iv2;
	private RelativeLayout animLayout, ll_root;
	private boolean isAnim = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		iv1 = (ImageView) findViewById(R.id.imageView1);
		iv2 = (ImageView) findViewById(R.id.imageView2);
		animLayout = (RelativeLayout) findViewById(R.id.anim_layout);
		ll_root = (RelativeLayout) findViewById(R.id.ll_root);
		findViewById(R.id.button1).setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(isAnim)   //防止动画时点击,出现一系列异常
					return;
				animLayout.setVisibility(View.VISIBLE);//显示动画层
				animLayout.removeAllViews();//并且移除掉动画层中的组件
				ImageView i1 = createAnimView(iv1);
				ImageView i2 = createAnimView(iv2);
				createAndStartAnim(i1, i2);
			}
		});
	}

	private void createAndStartAnim(ImageView i1, ImageView i2) {
		TranslateAnimation anim1 = new TranslateAnimation(0, iv2.getLeft()
				- iv1.getLeft(), 0, iv2.getTop() - iv1.getTop());
		anim1.setFillAfter(true);
		anim1.setDuration(200);

		TranslateAnimation anim2 = new TranslateAnimation(0, iv1.getLeft()
				- iv2.getLeft(), 0, iv1.getTop() - iv2.getTop());
		anim2.setFillAfter(true);
		anim2.setDuration(200);
		
		i1.startAnimation(anim1);
		i2.startAnimation(anim2);
		
		anim1.setAnimationListener(new AnimationListener() {
			
			@Override
			public void onAnimationStart(Animation animation) {
				iv1.setVisibility(View.INVISIBLE);
				iv2.setVisibility(View.INVISIBLE);
				isAnim = true;
			}
			
			@Override
			public void onAnimationRepeat(Animation animation) {
				
			}
			
			@Override
			public void onAnimationEnd(Animation animation) {
				Drawable d1 = iv1.getDrawable();
				Drawable d2 = iv2.getDrawable();
				iv1.setImageDrawable(d2);
				iv2.setImageDrawable(d1);
				iv1.setVisibility(View.VISIBLE);
				iv2.setVisibility(View.VISIBLE);//交换实际组件中的image
				animLayout.setVisibility(View.INVISIBLE);//隐藏掉动画层中的组件
				//animLayout.removeAllViews();此处执行时会报错
				isAnim = false;
			}
		});
	}

	private ImageView createAnimView(ImageView src) {
		LayoutParams lp = new LayoutParams(src.getWidth(), src.getHeight());
		lp.leftMargin = src.getLeft() - ll_root.getPaddingLeft();
		lp.topMargin = src.getTop() - ll_root.getPaddingTop();
		Drawable d = src.getDrawable();
		ImageView i1 = new ImageView(this);
		i1.setImageDrawable(d);
		animLayout.addView(i1, lp);
		return i1;
	}


你可能感兴趣的:(动画层)