一直以来我都想好把 textview 好好整整,这不现在得着机会了,还不走起,等着干啥......
先看效果:

项目地址:BW_Libs
实现思路
所谓翻转,就是 A 面 B 面的切换,和磁带正反面很像的。看图很容易就让我们想起用 rotationY 这个属性来做动画,在动画执行一半之后,切换 view 的显示。 所以我试了试,我用属性动画做的:
-
先用的 0-180 的动画,发现有些问题。在翻转 90 之后,view 的内容也跟着翻转了,文字都是反的着明显不行
-
然后我拆成 2个动画,0-90,90-180,都不行,view 内容还是反着的,我想想,属性都改了,显示肯定也跟着走啊,只要过 90度 都行不啊
然后我看到着篇文章:Android自定义控件之翻转按钮,发现原来是从 0-90,-90-0。我 CAO 了,原来是负数的啊,思维定势害死人啊,百思不得其姐的事原来这么简单,看来从小学的政治最常说的:解放思想,真是至理名言啊,主席诚不欺我也~
动画代码
我把动画部分抽象了一下,做成了一个辅助工具类,因为不光 textview 可以用,只要是 view 都可以用,着应该属于 layout 动画的范畴了吧
ps:我用 button 试了下,发现有蛋疼的阴影扩散问题,可难看了,所以这里用 textview 代替 button
动画辅助类:
class LayoutRotationAnimator(view: View, time: Long = 300) {
/**
* 画面切换时显示监听器
*/
interface IStateChangeListener {
fun showA()
fun showB()
}
// A面 = 正面
var STATE_A: Int = 1
// B面 = 反面
var STATE_B: Int = -1
// 当前在哪面
var currentState: Int = STATE_A
// A 面动画
var animatorA: ObjectAnimator
// B 面动画
var animatorB: ObjectAnimator
// 面切换时显示变化
lateinit var stateChangeListener: IStateChangeListener
init {
animatorA = ObjectAnimator.ofFloat(view, "rotationY", 0f, 90f).setDuration(time)
animatorB = ObjectAnimator.ofFloat(view, "rotationY", -90f, 0f).setDuration(time)
animatorA.addListener(object : Animator.AnimatorListener {
override fun onAnimationRepeat(animation: Animator?) {
}
override fun onAnimationEnd(animation: Animator?) {
view.rotationY = 0f
changeState()
animatorB.start()
}
override fun onAnimationCancel(animation: Animator?) {
}
override fun onAnimationStart(animation: Animator?) {
}
})
}
fun start() {
animatorA.start()
}
/**
* 画面更新时切换显示
*/
private fun changeState() {
if (currentState == STATE_A) {
currentState = STATE_B
stateChangeListener?.showB()
} else {
currentState = STATE_A
stateChangeListener?.showA()
}
}
}
布局使用:
class TextViewActivity : AppCompatActivity() {
lateinit var layoutAnimator: LayoutRotationAnimator
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_text_view)
layoutAnimator = LayoutRotationAnimator(btn01)
layoutAnimator.stateChangeListener = object : LayoutRotationAnimator.IStateChangeListener {
override fun showA() {
btn01.setText("正面")
btn01.setBackgroundColor(Color.BLUE)
}
override fun showB() {
btn01.setText("反面")
btn01.setBackgroundColor(Color.RED)
}
}
btn01.setOnClickListener({
layoutAnimator.start()
})
}
}
网友评论