Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Android

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

Hello,

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:

relativeLayout.setBackgroundResource(getBackground());

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.