Android background image

Sometimes, you probably want to change the background of an activity to a different image. In this Android tip, I am going to show you how to achieve this goal.
To set the background image of an activity, you set the background image of the parent layout of the activity. The parent layout of the activity can be RelativeLayout, LinearLayout, FrameLayout, etc. There two methods of the parent layout object you can use. They are setBackground() and setBackgroundResource(). You need to pass a Drawable object that encapsulate the image to the setBackground() method. This method works in Android level 16 and higher. The setBackgroundResource() method works in lower levels of Android. It accepts a drawable resource id that points to the image in res/drawable folder. In code, you should check the Android level before applying the methods.

Now to have an example application on setting background image to the activity, you create a new Android project called ImgBackground. Then, in the activity_main.xml file, you add an id attribute to the parent layout so that you can make a reference to it later in code.

<RelativeLayout xmlns:android= ""
   tools:context= "com.example.imgbackground.MainActivity"

     android:text="@string/hello_world" />


In the res/drawable folder, you need an image that will be used as the background image of the activity. In my case, the image is Angkor.png.
Here is the code written in the MainActivity class to set the background image of the activity using two methods as mentioned above.

package com.example.imgbackground;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;

public class MainActivity extends ActionBarActivity {

protected void onCreate(Bundle savedInstanceState) {

// Reference to the parent layout
RelativeLayout layoutparent = (RelativeLayout) findViewById(;
// Set the image to background of the activity
Drawable backgroundImage = getResources().getDrawable(R.drawable.angkor);
layoutparent.setBackgroundResource (R.drawable.angkor);




Posted by: Dara | post date: 11-22-2014 | Subject: Android Apps Development

write programming tip

This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages:
C, C++, C#, Java, VB.NET, Python, VBA,PHP & Mysql, SQL, JSP, ASP.NET,HTML, CSS, JQuery, JavaScript and other applications such as MS Excel, MS Access, and MS Word. However, we don't guarantee all things of the web are accurate. If you find any error, please report it then we will take actions to correct it as soon as possible.