How to get accent color programmatically?

前端 未结 7 2405
没有蜡笔的小新
没有蜡笔的小新 2020-12-05 03:32

How would one fetch the accent color set in styles, like below, programmatically?

    @color/material_green_500<         


        
7条回答
  •  天涯浪人
    2020-12-05 04:20

    Here's my take on this:

    public static String getThemeColorInHex(@NonNull Context context, @NonNull String colorName, @AttrRes int attribute) {
        TypedValue outValue = new TypedValue();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            context.getTheme().resolveAttribute(attribute, outValue, true);
        } else {
            // get color defined for AppCompat
            int appCompatAttribute = context.getResources().getIdentifier(colorName, "attr", context.getPackageName());
            context.getTheme().resolveAttribute(appCompatAttribute, outValue, true);
        }
        return String.format("#%06X", (0xFFFFFF & outValue.data));
    }
    

    Usage:

        String windowBackgroundHex = getThemeColorInHex(this, "windowBackground", android.R.attr.windowBackground);
        String primaryColorHex = getThemeColorInHex(this, "colorPrimary", R.attr.colorPrimary);
    

提交回复
热议问题