Android动态修改状态栏沉浸色(取图片颜色)

时间:2024-05-19 16:24:07

项目要求  滑动图片卡,背景会自动变色,并且动态修改状态栏沉浸色

Android动态修改状态栏沉浸色(取图片颜色)

Android动态修改状态栏沉浸色(取图片颜色)





关键代码 :

在图片切换的回调接口中

执行

Bitmap bit = drawableToBitmap(resource);
int pixel = bit.getPixel(resource.getIntrinsicWidth()/ 2,0);//取图片最上面的中间色图
int redValue = Color.red(pixel);
int blueValue = Color.blue(pixel);
int greenValue = Color.green(pixel);
int alpha = Color.alpha(pixel);

StatusBarCompat.compat(getActivity(),  Color.argb(alpha, redValue, greenValue, blueValue));//StatusBarCompat为修改状态栏工具类




public class StatusBarCompat {
    private static final int INVALID_VAL = -1;
    private static final int COLOR_DEFAULT = Color.parseColor("#00000000");

    public static void compat(Activity activity, int statusColor) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            if (statusColor != INVALID_VAL) {
                activity.getWindow().setStatusBarColor(statusColor);
            }
            return;
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            int color = COLOR_DEFAULT;
            ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
            if (statusColor != INVALID_VAL) {
                color = statusColor;
            }
            statusBarView = new View(activity);
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    getStatusBarHeight(activity));
            statusBarView.setBackgroundColor(color);
            contentView.addView(statusBarView, lp);
        }

    }

    public static void Clean(Activity activity, int statusColor) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            ViewGroup contentView = (ViewGroup) activity.findViewById(android.R.id.content);
            contentView.removeView(statusBarView);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
             activity.getWindow().setStatusBarColor(statusColor);
        }
    }

    private static View statusBarView;

    public static void compat(Activity activity) {
        compat(activity, INVALID_VAL);
    }


    public static int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }
}
StatusBarCompat工具类取自网络,在其基础上加了Clean方法,其原因因为fragment基于activity,修改单个fragment状态栏,其它fragment状态栏也会变色。。  要求只修改 图片卡这个fragment的状态栏,其他fragment的状态栏 都为fragment白色默认色,在图片卡这个fragment中

public void onPause() {
    super.onPause();
    StatusBarCompat.Clean(getActivity(),Color.WHITE);
}