最近遇到一个需求,类似于12306买火车票那样,点击switch按钮,将起始地点和目的地点的文本做一个交换,废话不多说先上图看下最终效果。
如果直接设置两边的TextView的文本的话显得太呆板,所以要加一个交换的动画。在网上找了很久,主要是两种实现方式,第一种是将两边的TextView画成两个bitmap,再去做处理(有点麻烦,没细看),第二种是自定义View。这么一个简单的需求做那么麻烦,这肯定不行,太费脑细胞了😢,所以自己研究了一种方式,直接采用ObjectAnimator使用动画来实现,核心代码还不到20行,界面代码就不沾上来了。直接上核心的文本交换代码
private fun initAnim() {
val startTV = addressStartTV ?: return
val endTV = addressEndTV ?: return
val iconSwitch = switchIV ?: return
val startAnimator = if (isSwitch) {
ObjectAnimator.ofFloat(startTV, "translationX", (startTV.width + iconSwitch.width).toFloat(), 0f)
} else {
ObjectAnimator.ofFloat(startTV, "translationX", 0f, (startTV.width + iconSwitch.width).toFloat())
}
startAnimator.duration = 1000
startAnimator.start()
val endAnimator = if (isSwitch) {
ObjectAnimator.ofFloat(endTV, "translationX", -(startTV.width + iconSwitch.width).toFloat(), 0f)
} else {
ObjectAnimator.ofFloat(endTV, "translationX", 0f, -(startTV.width + iconSwitch.width).toFloat())
}
endAnimator.duration = 1000
endAnimator.start()
}
源码以开源到gitee,菜鸟一枚,如有大佬有更好的方法欢迎指教,瑞思拜!!!