WindowManager addViw 添加自定义动画效果

业务需要一个优先级较高的窗口,在任何界面都能随时弹出,且需要实现底部弹出及收起的动画效果。

选择使用**windowManager.addView()**添加布局,在添加动画效果时发现给布局直接添加动画效果如:

val animationUp = AnimationUtils.loadAnimation(mContext, R.anim.pop_enter_anim);
inCallView.startAnimation(animationUp)

或通过WindowManager.LayoutParamswindowAnimations方法设置动画效果

params.windowAnimations = R.style.popwin_anim

两种实现方式均无效

通过给布局最外层嵌套一层布局实现了最终的效果,代码如下,供大家参考

    private var mParentView: FrameLayout? = FrameLayout(mContext)
    private var inCallView = View.inflate(context.applicationContext, R.layout.layout_call, null)
    private val windowManager: WindowManager by lazy {
        val windowManager =
            mContext.applicationContext.getSystemService(Context.WINDOW_SERVICE) as WindowManager
        mParentView?.addView(inCallView)
        windowManager
    }
    private val params: WindowManager.LayoutParams by lazy {
        val params = WindowManager.LayoutParams()
        @Suppress("DEPRECATION") //只有SYSTEM_ERROR才能覆盖到systemUI之上
        params.type = WindowManager.LayoutParams.TYPE_PHONE
        params.flags =
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
        params.format = PixelFormat.TRANSLUCENT
        params.width = WindowManager.LayoutParams.MATCH_PARENT
        params.height = WindowManager.LayoutParams.WRAP_CONTENT
        params.x = -1
        params.y = -1
        params.gravity = Gravity.BOTTOM
        params
    }

    fun show() {
        windowManager.addView(mParentView, params)
        val animationUp =
            AnimationUtils.loadAnimation(mContext, R.anim.pop_enter_anim);
        inCallView.startAnimation(animationUp)
    }

    fun dismiss() {
        val animationDown = AnimationUtils.loadAnimation(mContext, R.anim.pop_exit_anim);
        inCallView.startAnimation(animationDown)
        handler.postDelayed(Runnable {
            windowManager.removeView(mParentView)

        }, 500)
    }

动画效果pop_exit_animpop_enter_anim

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <!-- 平移动画 -->
    <translate
        android:duration="500"
        android:fromYDelta="0"
        android:toYDelta="100%" />

</set>
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:shareInterpolator="false">
    <!-- 平移动画 -->
    <translate
        android:duration="500"
        android:fromYDelta="100%"
        android:toYDelta="0" />
</set>
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐