Android SDK – Changing background of a layout at run time

I was working on a android project where I had to change background image in a layout at at run time. For instance, the user selects an image and it becomes the background of the layout. It is fairly simple to do in Android. See below on how I achieved it:

I have a Frame Layout in which I have defined a background in my case the image file name is “wooden.png” so I have, ‘ android:background=”@drawable/wooden” ‘ in the layout definition. By having this line in my layout, Android will use the wooden.png  that is in the “drawable” directory as the background for the activity .

See below for xml extract:

<FrameLayout xmlns:android=""	android:id="@+id/main_layout"    android:orientation="vertical"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:background="@drawable/wooden">

.. ...



In the code if I want to change the background I could achieve this by calling “setBackgroundResource” method on the layout.

See below for an example.


View mainLayout = findViewById(; // getting the layout

mainLayout.setBackgroundResource(R.drawable.stone); // changing the background to 'stone.png'




2 thoughts on “Android SDK – Changing background of a layout at run time

    1. Good question Carl.
      Inside the “res” folder, you can create a folder called “drawable” if it doesn’t exist already. place image files in there.
      R will be dynamically generated to represent each files that in that folder.
      Hope this answers your question.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s