How to tile a background image in Android

Posted: June 11, 2011 in Android

How to tile a background image in Android

For one of the apps I’m working on I wanted to have a nice pixel pattern tiled behind my widgets.
After a little bit of hunting around I found this tutorial, and I thought I’d clean up the lessons within and show you how.

Here’s the contents of my main.xml layout file,

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@drawable/backrepeat" android:gravity="center_horizontal" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/hello" />  

which is referenced in code in the standard way like this:

 @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); 
...// (rest of onCreate method continues here..)

Now note this line:


What’s going on there?
.. Glad you asked!

Here’s a quick screenshot of the contents of one of my drawable folders in my project:

What is this

Well, here’s the contents of that file here:

android:dither="true" />

Can you see what’s going on?
Backrepeat.xml defines an instance of the BitmapDrawable class, and that class references our simple scale1.jpg, located in the drawable-hdpi folder.

Simply by adding the:

<bitmap xmlns:android="" android:src="@drawable/scale1" android:tileMode="repeat" android:dither="true" /> 

line in bold, we are able to achieve results such as this:

Easy isn’t it?

One thing to keep in mind is that you should have folders drawable-hdpi, drawable-mdpi & drawable-ldpi, you’ll need to add this backrepeat.xml file and the relevant images to each of these to allow this functionality in high, medium and low dpi (dots per inch) screen sizes.




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 )

Google+ photo

You are commenting using your Google+ 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