设置Activity背景为透明色

2020-04-10  本文已影响0人  小相柳

设置Activity的背景为透明色,除了自定义Theme之外,要动态设置可以使用以下方式实现

private void convertActivityToTranslucent(Activity activity) {
        if (activity == null || activity.isTaskRoot()) return;
        try {
            Class[] clazzArray = Activity.class.getDeclaredClasses();
            Class mTranslucentConversionListenerClass = null;
            for (Class clazz : clazzArray) {
                if (clazz.getSimpleName().contains("TranslucentConversionListener")) {
                    mTranslucentConversionListenerClass = clazz;
                }
            }
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Object options = null;
                try {
                    Method getActivityOptions = Activity.class.getDeclaredMethod("getActivityOptions");
                    getActivityOptions.setAccessible(true);
                    options = getActivityOptions.invoke(activity);
                } catch (Exception ignored) {
                }
                Method convertToTranslucent = Activity.class.getDeclaredMethod("convertToTranslucent", mTranslucentConversionListenerClass, ActivityOptions.class);
                convertToTranslucent.setAccessible(true);
                convertToTranslucent.invoke(activity,  null, options);
            } else {
                Method convertToTranslucent = Activity.class.getDeclaredMethod("convertToTranslucent", mTranslucentConversionListenerClass);
                convertToTranslucent.setAccessible(true);
                convertToTranslucent.invoke(activity, (Object) null);
            }
            getWindow().setBackgroundDrawableResource(R.color.translucent);
        } catch (Throwable e) {
            //异常情况设置透明背景失败
            e.printStackTrace();
        }
    }
上一篇下一篇

猜你喜欢

热点阅读