开始看到这个需求,准备使用视图动画 TranslateAnimation 来实现。但是把因为视图动画只是移动了视图,控件的位置没有改变,导致只能执行一次交换的动作,不能交换回来。逐放弃改用属性动画来实现。直接交换两个控件的位置,交换后在将原来控件的值赋予交换后的控件。
垂直交换的动画
if (startView.getTranslationY() ==0) {
//顶部控件平移动画 从当前坐标0.0 移动到需要交换位置的控件Y坐标(endView.getY())加底部控件的高度减去上边控件的高度得到的差值(endView.getHeight() - startView.getHeight()) 为上下控件大小不一后也能正常位移
startAnimator = ObjectAnimator.ofFloat(startView, View.TRANSLATION_Y, startView.getTranslationY(), endView.getY() + (endView.getHeight() - startView.getHeight()));
//底部控件平移动画 从当前坐标0.0 移动当前父布局中的最底部替换了顶部布局。
endAnimator = ObjectAnimator.ofFloat(endView, View.TRANSLATION_Y, endView.getTranslationY(), -endView.getY());
}else {
//已经平移过后,将平移的距离回退回去
startAnimator = ObjectAnimator.ofFloat(startView, View.TRANSLATION_Y, startView.getTranslationY(), -startView.getY());
endAnimator = ObjectAnimator.ofFloat(endView, View.TRANSLATION_Y, endView.getTranslationY(), startView.getY());
}
如果业务需求使用水平排列的布局,只需要将布局中的控件水平排列,之后将交换的动画Y轴全部替换成X轴,高度替换为宽度。
if (startView.getTranslationX() ==0) {
//顶部控件平移动画 从当前坐标0.0 移动到需要交换位置的控件X坐标(endView.getX())加底部控件的高度减去上边控件的高度得到的差值(endView.getWidth() - startView.getWidth()) 为上下控件大小不一后也能正常位移
startAnimator = ObjectAnimator.ofFloat(startView, View.TRANSLATION_X, startView.getTranslationX(), endView.getX() + (endView.getWidth() - startView.getWidth()));
//底部控件平移动画 从当前坐标0.0 移动当前父布局中的最底部替换了顶部布局。
endAnimator = ObjectAnimator.ofFloat(endView, View.TRANSLATION_X, endView.getTranslationX(), -endView.getX());
}else {
//已经平移过后,将平移的距离回退回去
startAnimator = ObjectAnimator.ofFloat(startView, View.TRANSLATION_X, startView.getTranslationX(), -startView.getX());
endAnimator = ObjectAnimator.ofFloat(endView, View.TRANSLATION_X, endView.getTranslationX(), startView.getX());
}
控件的实现并不多,我就直接将完整的实现粘贴在这,在获取控件内容和保存的对象的时候如果有更好的方法欢迎留言。
垂直交换控件的完整实现
import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class LocationExchangeView extends LinearLayout implements View.OnClickListener {
public interface OnViewChangeListener {
void onStartCallback();
void onEndCallback();
}
private OnViewChangeListener l;
public TextView startLocationView, endLocationView;
public ImageView locationExchangeBtn;
public LinearLayout locationLayout;
private boolean isChange;
private