Android 对 ActionBar 上的 Icon 添加动画

View Animation

override fun onDestroy() {
    super.onDestroy()
    menu.findItem(R.id.setting).actionView?.clearAnimation()
}

private fun initAnim() {
    val setting = menu.findItem(R.id.setting)
    setting.actionView = ImageView(this).apply {
        setImageDrawable(setting.icon)
        startAnimation(AnimationUtils.loadAnimation(context, R.anim.anim_main_activity_setting))
        // 设置了 actionView 后点击不再自动回调 onOptionsItemSelected,
        // 但是当图标被收纳到更多按钮里去后,还是会回调 onOptionsItemSelected
        setOnClickListener {
            SettingActivity.start()
        }
        // 同时,也不再自动显示长按提示,需要手动添加长按提示
        TooltipCompat.setTooltipText(this, setting.title)
    }
}


View Animation.gif

Property Animaton

private fun initAnim() {
    val search = menu.findItem(R.id.search)
    search.actionView = ImageView(this).apply {
        setImageDrawable(search.icon)
        setOnClickListener {
            SearchActivity.start(eventId)
        }
        TooltipCompat.setTooltipText(this, search.title)

        // 为了获取 width 和 height,需要 post
        post {
            val path = Path()
            path.addCircle(width / 2f, height / 2f, width / 8f, Path.Direction.CW)
            val pathMeasure = PathMeasure(path, true)
            val valueAnimator = ValueAnimator.ofFloat(0f, pathMeasure.length)
            valueAnimator.duration = 1500L
            valueAnimator.interpolator = LinearInterpolator()
            valueAnimator.repeatCount = ValueAnimator.INFINITE
            val currentPosition = FloatArray(2)
            valueAnimator.addUpdateListener { animation ->
                if (lifecycle.currentState == Lifecycle.State.DESTROYED) {
                    valueAnimator.cancel()
                    // LogUtils.d("search animator canceled...")
                } else {
                    val value = animation.animatedValue as Float
                    pathMeasure.getPosTan(value, currentPosition, null)
                    translationX = currentPosition[0] - width / 2f
                    translationY = currentPosition[1] - height / 2f
                    // LogUtils.d("search animator running...")
                }
            }
            valueAnimator.start()
        }
    }
}
Property Animaton.gif

你可能感兴趣的:(Android 对 ActionBar 上的 Icon 添加动画)