Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

Random Gradient Background?

I was wondering how to create a random gradient for the Fun Facts Activity. I was able to get a gradient going using a gradient selector in a gradient.xml under the drawable folder and it displays the gradient correctly.

<?xml version="1.0" encoding="utf-8"?> <selector xmlns:android="http://schemas.android.com/apk/res/android"> <item> <shape> <gradient android:angle="90" android:startColor="#FF176D9A" android:endColor="#FF229CDC" android:type="linear" /> </shape> </item> </selector>

...but I can't figure out how to create multiple gradients similar to the array of colors, and then have it pull those instead of the plain colors. Any help would be appreciated! :)

3 Answers

Hello Jeff,

Sorry about the delayed response, I think I have something that will work for you.

So, I added a String[] to the color wheel class, so that portion of the class will look like this:

public class ColorWheel {



    private String mColors[] = {
             "#39add1", // light blue [0]
            "#3079ab", // dark blue [1]
            "#c25975", // mauve [2]
            "#e15258", // red
            "#f9845b", // orange
            "#838cc7", // lavender
            "#7d669e", // purple
            "#53bbb4", // aqua
            "#51b46d", // green
            "#e0ab18", // mustard
            "#637a91", // dark gray
            "#f092b0", // pink
            "#b7c0c7"  // light gray
    };

    private String mColors2[] = {
            "#3079ab", //dark blue  [0]
            "#39add1", // light blue [1]
            "#e0ab18", // mustard [2]
            "#637a91", // dark gray
            "#f092b0", // pink
            "#b7c0c7",  // light gray
            "#c25975", // mauve
            "#51b46d", // green
            "#e15258", // red
            "#f9845b", // orange
            "#838cc7", // lavender
            "#7d669e", // purple
            "#53bbb4", // aqua
    };

So basically the color codes which inhabit each spot (i.e - [0], [1], [2]) will become a gradient with it's counterpart between the two string arrays. So in spot [0] you should have the colors which you would like paired. Currently it is set to "Light blue" in "mColors[]", and "Dark blue" in "mColors2[]".

Now we have to add a new method to get these which will look similar to our getColor method in our ColorWheel class.

    public int[] getGcolors() {
        String color = "";
        String color2 = "";

        Random randomGenerator = new Random();
        int randomNumber = randomGenerator.nextInt(mColors.length);

        color = mColors[randomNumber];
        color2 = mColors2[randomNumber];
        int colorAsInt = Color.parseColor(color);
        int colorAsInt2 = Color.parseColor(color2);

        return new int[] {colorAsInt, colorAsInt2};

Ok, so now we have two colors, from two seperate arrays, but we're using the same "random number" for both. Which is going to be very helpful right away.

In our Main Activity, my onClickListener now looks like this:

 View.OnClickListener listener = new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View v) {
                String fact = mFactBook.getFact();

                // update label with dynamic fact
                factLabel.setText(fact);

                int color = mColorWheel.getColor();
                int[] gColors = mColorWheel.getGcolors();

                GradientDrawable gd2 = new GradientDrawable(
                        GradientDrawable.Orientation.TOP_BOTTOM,
                        new int[] {gColors[0], gColors[1]});
                        gd2.setCornerRadius(0f);

                relativeLayout.setBackground(gd2);
                showFactButton.setTextColor(color);
            }
        };

Alright. So now our gradient will be based on the result of two color codes, each pulled from a seperate array, but from the same array number, if that makes sense, haha. You may have to put a little work into which colors go with what, and placing them in the right spots, but this is a good first step I believe.

Let me know if this works for you, Joe

Awesome, everything works great now! Thanks SO much for all your help Joe!

Hello! I thought this was an interesting question so I've been playing around a bit in Android Studio. I'm also using the funFacts activity, so I have the same resources you do at the moment. In my mainActivity I changed my setBackground portion of my onClickListener() to :

        View.OnClickListener listener = new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View v) {
                String fact = mFactBook.getFact();

                // update label with dynamic fact
                factLabel.setText(fact);

                int color1 = mColorWheel.getColor();
                int color2 = mColorWheel.getColor();

             GradientDrawable gd = new GradientDrawable(
                        GradientDrawable.Orientation.TOP_BOTTOM,
                        new int[] {color1, color2});
                gd.setCornerRadius(0f);

                relativeLayout.setBackground(gd);

                showFactButton.setTextColor(color2);
            }
        };

This basically creates a new Gradient Drawable using two Random Colors generated from our ColorWheel class. Let me know if it works for you

Also, this is kind of a cool effect, using three colors instead of just two by changing this line:

    new int[] {color1, color2});

to this line:

    new int[] {color1, color2, color1});

I also have to agree with Joseph on this one - this seems to be the best way to go about it. +1 for the answer :)

EDIT: Scratch the error, got it to work! But still wondering if there's a way to set specific gradients?

Hmm...getting a "Non-static method 'setBackground(android.graphics.drawable.Drawable)' cannot be referenced from a static context" error for setBackground here...

relativeLayout.setBackground(gd);

Also, will this pull random colors and create a random gradient like pink to green? Any way to set an array of gradients to keep the colors uniform like something light blue->blue, light green->green, etc?

Thank you for the help!

Hello,

I'm not 100% sure if this is what you are looking for, but this posting on stackoverflow might be what you are looking for.