我想在状态栏上的显示切口后面放置一个不可见的按钮。我不想像其他代码一样向用户显示通知,而是在状态栏上显示一个不可见的按钮。我添加了代码来检测显示切口的大小和位置,但我无法在状态栏上放置按钮状态栏位于显示切口的正后方。我想让用户点击相机凹口,并且相机凹口后面应该有一个看不见的按钮。
在AndroidManifest.xml中添加
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
必须在运行时请求此权限:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, PERMISSION_CODE);
}
检测显示切口
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES;
// Apply layoutParams to your window or view
}
创建和定位隐形按钮
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN,
PixelFormat.TRANSLUCENT);
// Assuming you have the cutout position and size (cutoutRect)
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = cutoutRect.left; // Position X
params.y = cutoutRect.top; // Position Y
params.width = cutoutRect.width(); // Width of the cutout
params.height = cutoutRect.height(); // Height of the cutout
Button invisibleButton = new Button(this);
invisibleButton.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
invisibleButton.setBackgroundColor(Color.TRANSPARENT); // Making the button invisible
invisibleButton.setOnClickListener(v -> {
Toast.makeText(this, "Notch tapped!", Toast.LENGTH_SHORT).show();
});
windowManager.addView(invisibleButton, params);