Vik0809
Vik0809

Reputation: 379

set background to gradient color

I want to set the background of my actionbar to a gradient color. For that I have a Colorpicker, in which I can choose the start and the end color. I would like to use these values to set the background.

But I don't know in which format the int values should be to set the gradient drawable to the actionbar. At first I thought the format should something like: #FFFFFFF like I use in that case: actionbar.setBackgroundDrawable(new ColorDrawable(Color.parseColor(hexFarbe))); for example.

I tried it with this:

 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);
        }

Here I want to set the actionbar color:

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);
}

But then I get the following logcat error:

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

Upvotes: 0

Views: 192

Answers (1)

Ed Holloway-George
Ed Holloway-George

Reputation: 5149

You are getting a NumberFormatException as the # within the string you are providing cannot be handled by the parseInt() method.

When working with a color string, instead of Integer.parseInt() try the Color class' method:

public static int parseColor (String colorString)

From the Android documentation:

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

Upvotes: 3

Related Questions