将背景设置为渐变色

set background to gradient color

我想将操作栏的背景设置为渐变色。为此,我有一个 Colorpicker,我可以在其中选择开始和结束颜色。我想使用这些值来设置背景。

但我不知道 int 值应该采用哪种格式来将渐变可绘制对象设置为 actionbar。起初我认为格式应该是这样的:#FFFFFFF 就像我在那种情况下使用的那样:例如 actionbar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(hexFarbe)));

我试过这个:

 if (x > 10 && x < 138 && y > 316 && y < 356){
            endfarbe_zuletzt_gewählt_global = false;
            startfarbe_zuletzt_gewählt_global = true;
            String hexColor = String.format("#%06X", (0xFFFFFF & startFarbe));
            Log.d("startfarbe", "startfarbe " + endFarbe + "|" + hexColor);
            startFarbe_global = hexColor;
            mListener.colorChanged("startFarbe", startFarbe);
        }

这里我想设置操作栏颜色:

if(!(startFarbe.equalsIgnoreCase(""))&&(!(endfarbe.equalsIgnoreCase("")))){
            GradientDrawable gd = new GradientDrawable(
                    GradientDrawable.Orientation.TOP_BOTTOM,
                   // new int[] {0xFF616261,0xFF131313});
                    new int[] {Integer.parseInt(startFarbe), Integer.parseInt(endfarbe)});

            actionbar.setBackgroundDrawable(gd);
}

但随后出现以下 logcat 错误:

Caused by: java.lang.NumberFormatException: Invalid int: "#0000FF"

您得到的是 NumberFormatException,因为 parseInt() 方法无法处理您提供的字符串中的 #

使用颜色字符串时,请尝试使用 Color class' 方法代替 Integer.parseInt()

public static int parseColor (String colorString)

来自Android documentation

Supported formats are: #RRGGBB #AARRGGBB 'red', 'blue', 'green', 'black', 'white', 'gray', 'cyan', 'magenta', 'yellow', 'lightgray', 'darkgray'