今天在做一个小功能模块的时候,需要对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。
这篇博客讲述了在Android中如何为WindowManager添加的View添加动画,通过创建View、设置LayoutParams、设置初始不可见、创建Handler更新View,并在需要时调用代码实现Alpha动画。对于更复杂的Scale和Translate动画,则需要自行计算坐标并更新View。
303





