美文网首页
设置Activity背景为透明色

设置Activity背景为透明色

作者: 小相柳 | 来源:发表于2020-04-10 16:19 被阅读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();
            }
        }
    

    相关文章

      网友评论

          本文标题:设置Activity背景为透明色

          本文链接:https://www.haomeiwen.com/subject/mvnrmhtx.html