ObjectAnimator 动画需要一个起点和终点,不指定起点 默认从0开始,导致有时候有入场动画没有出场动画
源码:
package com.example.androidstudiogiraffe.view
import android.animation.ObjectAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.util.AttributeSet
import androidx.appcompat.widget.AppCompatEditText
import com.example.androidstudiogiraffe.R
import com.future.startstudyproject.utils.dp
private val TEXTSIZE = 12.dp
private val TEXT_MARGIN = 8.dp
private val H_OFFSET = 5.dp
private val V_OFFSET = 23.dp
private val EXTRA_V_OFFSET = 16.dp
class MateriaEditText(context: Context, attrs: AttributeSet) :
AppCompatEditText(context, attrs) {
val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private var floatintlabelshown = false
var isShowTopHint = false
set(value) {
if (field != value) {
field = value
if (field) {
setPadding(paddingLeft, (paddingTop + TEXTSIZE + TEXT_MARGIN).toInt(), paddingRight, paddingBottom)
} else {
setPadding(paddingLeft, (paddingTop - TEXTSIZE - TEXT_MARGIN).toInt(), paddingRight, paddingBottom)
}
}
}
var floatingLabelFraction = 0f
set(value) {
field = value
invalidate()
}
private val animator by lazy {
ObjectAnimator.ofFloat(this, "floatingLabelFraction", 0f, 1f)
}
init {
paint.textSize = TEXTSIZE
val typeArr = context.obtainStyledAttributes(attrs,R.styleable.MateriaEditText)
isShowTopHint = typeArr.getBoolean(R.styleable.MateriaEditText_isShowTopHint,true)
}
override fun onTextChanged(
text: CharSequence,
start: Int,
lengthBefore: Int,
lengthAfter: Int
) {
if (isShowTopHint) {
if (floatintlabelshown && text.isEmpty()) {
floatintlabelshown = false
animator.reverse()
} else if (!floatintlabelshown && text.isNotEmpty()) {
floatintlabelshown = true
animator.start()
}
}
}
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
paint.alpha = (floatingLabelFraction * 0xff).toInt()
val currentVerValue = V_OFFSET + EXTRA_V_OFFSET * (1 - floatingLabelFraction)
canvas.drawText(hint.toString(), H_OFFSET, currentVerValue, paint)
}
}