你以一个20年Android开发的身份,帮我写一个Window单例工具类,传一个view进去,会用WindowManager 全屏显示/隐藏,不影响底层点击。有个方法可以把这个view返回出来。
时间: 2024-03-12 07:49:36 浏览: 134
好的,我可以帮你写一个Window单例工具类,代码如下:
```java
import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
/**
* Window单例工具类
*/
public class WindowUtil {
private static WindowUtil sInstance;
private WindowManager mWindowManager;
private View mView;
private WindowUtil(Context context) {
mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
}
public static WindowUtil getInstance(Context context) {
if (sInstance == null) {
synchronized (WindowUtil.class) {
if (sInstance == null) {
sInstance = new WindowUtil(context);
}
}
}
return sInstance;
}
/**
* 显示view
*/
public void showView(View view) {
if (mView != null) {
return;
}
mView = view;
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
layoutParams.format = PixelFormat.TRANSLUCENT;
layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR |
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
layoutParams.gravity = Gravity.TOP | Gravity.LEFT;
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.MATCH_PARENT;
mWindowManager.addView(view, layoutParams);
}
/**
* 隐藏view
*/
public void hideView() {
if (mView == null) {
return;
}
mWindowManager.removeView(mView);
mView = null;
}
/**
* 获取view
*/
public View getView() {
return mView;
}
}
```
这个工具类中包含3个方法:
1. `getInstance(Context context)`:获取单例对象。
2. `showView(View view)`:显示传入的view。
3. `hideView()`:隐藏当前显示的view。
4. `getView()`:获取当前显示的view。
其中,`showView(View view)` 方法中的 `WindowManager.LayoutParams` 中的 `type` 设置为 `TYPE_APPLICATION_OVERLAY` 可以使得view全屏显示并且不影响底层点击。
阅读全文