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


How do you randomly change the relative layout background with a picture?

I am making an app similar to the Fun Facts app but in this one instead of changing the background color i want to change it with a picture.

So I made an array of pictures:

public int[] mFondo = { R.drawable.heart, R.drawable.house_cane, R.drawable.house_caricatura, R.drawable.vicodin, };

And this is my getBackground method:

public int getBackground(){

Random generator = new Random();

int randomNumber = generator.nextInt(mBackground.length);

return mBackground[randomNumber]; }

But how do i make this: relativeLayout.setBackgroundColor(color); With a picture?

1 Answer


I haven't tried this out myself, but a quick search pulled up a question on stackoverflow. I suggest reading the post, but essentially, you need to do the following:


This is the second suggestion, there are a few others that can work as well.

It works but now I press the button and it takes too long to change the background and the text in the label. When it finally changes I press again the button and it crashes In the log says that it run out of memory

After rewatching the video for creating a login page for Ribbit(where a background image is set), available here. However, that isn't going to solve the out of memory error, that I will have to refer you to the android developer page here where they give many tips for dealing with images so that you don't run out of memory or bring your app to a crawl. It is a bit of reading though.