这几天看郭神的博客 Android属性动画完全解析(上),初识属性动画的基本用法之后,我自己突然想实现一种动画功能,就是我们在携程网、阿里旅行等等手机APP端买火车票的时候,看到有选择城市,那么就有出发城市和到达城市,也可以点击“切换”按钮就可以互换城市名,意思就可以买返程票了。你既然要去一个地方,那肯定你也要回来啊。这样就不用再重新选择城市了。点击“切换”的时候有个动画的效果,那我的代码如下:
public class MainActivity extends Activity implements OnClickListener { public static final int UPDATE_VIEW = 1; private TextView textview_depart_city; private TextView textview_arrive_city; private Button button; private Handler handler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_VIEW: showCitySwitchRotation(); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.aimation); textview_depart_city = (TextView) findViewById(R.id.tv_departcity); textview_arrive_city = (TextView) findViewById(R.id.tv_arrvivecity); button = (Button) findViewById(R.id.btn_switch); button.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_switch: new Thread(new Runnable() { @Override public void run() { Message message = new Message(); message.what = UPDATE_VIEW; handler.sendMessage(message); } }).start(); break; default: break; } } /** * 显示城市切换动画 */ private void showCitySwitchRotation() { float curXDepart = textview_depart_city.getX(); float curXArrive = textview_arrive_city.getX(); ObjectAnimator animatorDepart = ObjectAnimator.ofFloat(textview_depart_city, "x", curXArrive); ObjectAnimator animatorArraive = ObjectAnimator.ofFloat(textview_arrive_city, "x", curXDepart); AnimatorSet animSet = new AnimatorSet(); animSet.play(animatorDepart).with(animatorArraive); animSet.setDuration(1000); animSet.start(); } }
用属性动画实现的。代码如下: