Android中为WindowManager添加的View添加动画

来源:互联网 发布:2017年动漫推荐知乎 编辑:程序博客网 时间:2024/05/17 04:17

今天在做一个小功能模块的时候,需要对WindowManager添加一个view且需要动画来平滑过渡。但是尝试对view添加动画,发现该动画不work。在StackOverFlow上面也有很多人遇到此问题,也没用得到解答。后面通过采用不断更新View的方式来解决此问题。如果大家有什么好的解决方案,麻烦告知一下,谢谢。

1、首先创建该View

suspendView = LayoutInflater.from(this).inflate(R.layout.tap, null);

2、添加LayoutParams

suspendLayoutParams = new LayoutParams();suspendLayoutParams.type = LayoutParams.TYPE_PHONE; // 悬浮窗的类型,一般设为2002,表示在所有应用程序之上,但在状态栏之下suspendLayoutParams.format = PixelFormat.RGBA_8888;suspendLayoutParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL| LayoutParams.FLAG_NOT_FOCUSABLE; // 悬浮窗的行为,比如说不可聚焦,非模态对话框等等suspendLayoutParams.gravity = Gravity.TOP; // 悬浮窗的对齐方式suspendLayoutParams.alpha = 0.0f;suspendLayoutParams.width = mScreenWidth;suspendLayoutParams.height = mTapLinearLayoutTop;suspendLayoutParams.x = 0; // 悬浮窗X的位置suspendLayoutParams.y = mTitleTop - mStatusTop;// //悬浮窗Y的位置,此时需要减去statusbar的高度


3、设置该View为不可见状态,并且将view添加到Window中

suspendView.setVisibility(View.GONE);mWindowManager.addView(suspendView, suspendLayoutParams);


4、创建一个Handler用于更新View

Handler handler = new Handler(){    public void handleMessage(android.os.Message msg) {        if (suspendView != null) {    suspendView.setVisibility(View.VISIBLE);    suspendView.startAnimation(appearAnimation);    float alpha = suspendLayoutParams.alpha;    alpha = alpha +0.05f;    if (alpha <= 1.0f) {suspendLayoutParams.alpha = alpha;mWindowManager.updateViewLayout(suspendView, suspendLayoutParams);handler.sendEmptyMessageDelayed(ALPHA_MESSAGE, 20);    }  else {handler.removeMessages(ALPHA_MESSAGE);    }}    };}

5、在需要实现alpha动画的时候,调用如下代码

handler.sendEmptyMessageDelayed(ALPHA_MESSAGE, 10);

效果如下:


上面的仅仅是对简单的alpha动画简单的实现,对于scale,translate需要自己对其坐标轨迹进行计算,然后再更新view。


0 0