在Android系统中调出窗口涉及多种场景和机制,具体方法取决于窗口类型和开发需求:
1. Activity窗口
- 通过`startActivity()`启动新的Activity,系统自动创建窗口。
- 可在`AndroidManifest.xml`中配置`
- 使用`Intent`传递数据,例如:
java
Intent intent = new Intent(this, TargetActivity.class);
startActivity(intent);
2. Dialog窗口
- 系统对话框:调用`AlertDialog.Builder`创建,通过`show()`显示:
java
new AlertDialog.Builder(context)
.setTitle("标题")
.setMessage("内容")
.setPositiveButton("确认", null)
.show();
- 自定义Dialog:继承`Dialog`类,重写布局和逻辑,调用`show()`显示。
3. PopupWindow
- 通过`PopupWindow`实现悬浮窗口,需设置布局和触摸事件:
java
View popupView = LayoutInflater.from(context).inflate(R.layout.popup_layout, null);
PopupWindow popup = new PopupWindow(popupView, width, height, true);
popup.showAsDropDown(anchorView); // 基于某个View定位
- 可设置动画(`popup.setAnimationStyle()`)和背景灰化(`setBackgroundDrawable`)。
4. WindowManager添加系统级窗口
- 申请`SYSTEM_ALERT_WINDOW`权限,通过`WindowManager`添加View:
java
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
width, height,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, // 系统浮动窗口类型
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
);
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(floatingView, params);
- 注意:Android 8.0+需动态申请权限,且类型需为`TYPE_APPLICATION_OVERLAY`。
5. 分屏与多窗口模式
- 在Android 7.0+中,Activity可通过配置`android:resizeableActivity="true"`支持分屏。
- 使用`ActivityOptions`控制窗口大小和位置:
java
ActivityOptions options = ActivityOptions.makeBasic();
options.setLaunchBounds(new Rect(0, 0, 500, 800));
startActivity(intent, options.toBundle());
6. Toast提示框
- 调用`Toast.makeText().show()`快速显示临时消息:
java
Toast.makeText(context, "提示内容", Toast.LENGTH_SHORT).show();
- 可自定义布局(通过`setView()`)和位置(`setGravity()`)。
7. SurfaceView与Window的关系
- `SurfaceView`通过`SurfaceHolder`在独立线程绘制内容,本质是WindowManager管理的底层窗口,适用于高性能渲染(如视频、游戏)。
8. 窗口层级与Z-order
- 通过`Window.setLayout()`调整大小,`Window.setElevation()`控制层级(需API 21+)。
- 系统窗口(如状态栏)的层级由`WindowManager.LayoutParams.type`决定,数值越大显示越靠前。
9. 输入法窗口
- 通过`InputMethodManager`控制软键盘显示/隐藏:
java
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT); // 显示
imm.hideSoftInputFromWindow(view.getWindowToken(), 0); // 隐藏
关键注意事项:
系统级窗口需处理权限和适配不同Androi本;
避免内存泄漏(如Dialog持有Activity引用时需在`onDestroy()`销毁);
多窗口模式下需重写`onConfigurationChanged()`处理布局变更;
浮动窗口需考虑触摸事件冲突和用户体验设计。