在Android中,您可以通過設置WindowManager.LayoutParams的alpha屬性來調整窗口的透明度
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
public class WindowStateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
WindowManager.LayoutParams layoutParams = windowManager.getCurrentWindow().getAttributes();
layoutParams.alpha = 0.5f; // 設置透明度,范圍為0.0f(完全透明)到1.0f(完全不透明)
windowManager.updateWindowLayout(layoutParams);
}
}
}
public class MainActivity extends AppCompatActivity {
private WindowStateReceiver windowStateReceiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
windowStateReceiver = new WindowStateReceiver();
IntentFilter intentFilter = new IntentFilter(Intent.ACTION_SYSTEM_ALERT_WINDOW_STATE);
registerReceiver(windowStateReceiver, intentFilter);
}
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(windowStateReceiver);
}
}
現在,每當系統窗口狀態發生變化時,您的應用都會自動調整窗口透明度。請注意,這種方法可能不適用于所有Android版本和設備,因為某些設備可能會限制或禁止這種自定義窗口行為。