Monday, November 21, 2011

[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:text="@string/hello" />  </LinearLayout>

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

@Overridepublic 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:
<bitmapxmlns:android=""android:src="@drawable/scale1"android:tileMode="repeat"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.



Post a Comment