用过手机360和QQ手机管家等一些软件的朋友,会发现,在这些应用中,会出现一个悬浮窗体,例如QQ手机管家中打电话的场景:
这种窗体除了会显示外,还可以移动它的位置,并且一直显示。除了关闭当前程序外,窗口不会主动消失。其实,它的使用原理也很简单,就是借用了WindowManager这个管理类来实现的。
注意:要在AndroidManifest.xml中添加使用权限:
- <uses-permission
- android:name="android.permission.SYSTEM_ALERT_WINDOW" />
这里,我采用代码布局的方式,模仿了一下QQ这个界面效果:
- import android.content.Context;
- import android.widget.ImageView;
- import android.widget.LinearLayout;
- import android.widget.TextView;
-
- public class DesktopLayout extends LinearLayout {
-
- public DesktopLayout(Context context) {
- super(context);
- setOrientation(LinearLayout.HORIZONTAL);
- LayoutParams mLayoutParams = new LayoutParams(
- LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
- setLayoutParams(mLayoutParams);
-
-
- ImageView mImageView = new ImageView(context);
- mImageView.setImageResource(R.drawable.icon);
- addView(mImageView, mLayoutParams);
-
-
- TextView mTextView = new TextView(context);
- mTextView.setText("Hello");
- mTextView.setTextSize(30);
- addView(mTextView, mLayoutParams);
- }
- }
接下来,在activity中让它显示出来。首先要设置一下WindowManager.LayoutParams:
- mWindowManager = (WindowManager) getApplicationContext()
- .getSystemService("window");
-
- mLayoutParams = new WindowManager.LayoutParams();
-
- mLayoutParams.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT;
-
- mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
-
- mLayoutParams.format = PixelFormat.RGBA_8888;
-
- mLayoutParams.gravity = Gravity.TOP | Gravity.LEFT;
-
- mLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
- mLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
-
- mLayoutParams.x = 50;
- mLayoutParams.y = 50;
显示窗体与关闭窗体的方法:
- mWindowManager.addView(mDesktopLayout, mLayoutParams);
-
- mWindowManager.removeView(mDesktopLayout);
以下是activity的原代码,这里设计了一个双击关闭窗体的效果:
显示的效果:
悬浮窗体例子
http://blog.csdn.net/xyz_fly/article/details/7546096
android编程之悬浮窗体,布布扣,bubuko.com
android编程之悬浮窗体
原文:http://www.cnblogs.com/daishuguang/p/3873701.html