If you just point your UI element to an image resource, like this:
you won't get a tiled background. Instead, you'll get the image stretched to the element size! Really horrible, if that's not what you intended to do.
The trick is to create another XML file in the drawable directory.
This file contains configuration settings which describe how an image should behave when used as a tiling background:
<?xml version="1.0" encoding="utf-8"?> <bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/myBackgroundImage" android:tileMode="repeat" />
Let's assume you saved it as drawable/tiledBackground.xml. Now, in your UI element you just simply have to refer to this newly created XML file instead of referring to the background image:
It's as if the XML file creates a virtual image out of the original image, except the new image can be tiled. In fact, what we are creating with this XML is a BitmapDrawable.
In the documentation for that class we can see that android:tileMode accepts the following values:
- repeat (the expected, intuitive tiling),
- mirror (which makes a non seamless pattern seamless!),
- and clamp (which repeats the edge colour).
It first occurred to me that this approach of having to create an XML file for defining tiles was a little over the top, but then I thought that maybe it's very useful if you want to reuse the same settings across a large collection of items. For example, if you want to define your own collection of UI widgets. So I guess that in that context it makes sense...