全局浮动小窗口,类似于微信的语音通话全局小窗口,还有一些手机的桌面的全局操作按钮等,算是比较常用,简单记录一下。
实现原理:在Application中,getSystemService(Context.WINDOW_SERVICE)
获取WindowManager
,然后通过WindowManager
添加View, 手势滑动时实时更新该window的LayoutParams
的x | y
坐标。
核心代码:
Application中创建window:
public class App extends Application {
private SmallWindowView mWindowView;
private WindowManager mWindowManager;
private WindowManager.LayoutParams mLayoutParams;
public SmallWindowView getWindowView() {
return mWindowView;
}
public WindowManager getWindowManager() {
return mWindowManager;
}
public WindowManager.LayoutParams getLayoutParams() {
return mLayoutParams;
}
@Override
public void onCreate() {
super.onCreate();
initSmallViewLayout();
}
public void initSmallViewLayout() {
mWindowView = (SmallWindowView) LayoutInflater.from(this).inflate(R.layout.small_window, null);
mWindowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
mLayoutParams = new WindowManager.LayoutParams(
getResources().getDimensionPixelSize(R.dimen.small_window_size), // 120dp
getResources().getDimensionPixelSize(R.dimen.small_window_size),
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
mLayoutParams.gravity = Gravity.NO_GRAVITY;
mWindowView.setWm(mWindowManager);
mWindowView.setWmParams(mLayoutParams);
}
public void showWindowView() {
if (mWindowManager != null && mWindowView.getWindowId() == null) {
mWindowManager.addView(mWindowView, mLayoutParams);
}
}
public void dismissWindowView() {
if (mWindowManager != null && mWindowView != null && mWindowView.getWindowId() != null) {
mWindowManager.removeView(mWindowView);
}
}
}
定义一个View组件,内部处理滑动改变窗口位置参数:
public class SmallWindowView extends LinearLayout {
private final static String TAG = SmallWindowView.class.getSimpleName();
private final int screenHeight;
private final int screenWidth;
private int statusHeight;
private float mTouchStartX;
private float mTouchStartY;
private float mLastRawX;
private float mLastRawY