Android tiled background

When creating background panels for various Android applications, we can use a static image that would scale or stretch or multiple images for multiple screen sizes, but we can also use a tiny image and repeat it on both axes for a tiled background.
android_tiled_background
As I am not a big fan of using XML static UI resources for Android development, my approach uses Java entirely. Place a small image to be used for our repeating background, such as this one:
background_pattern
It can be any image, but you’ll want the margins to match when the image gets repeated on horizontal and vertical axes.
Next, in your main activity, create a layout, load the image, set it to repeat, and add it as layout background.

// create tiled background
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.background_pattern);
BitmapDrawable bitmapDrawable = new BitmapDrawable(bmp);
bitmapDrawable.setTileModeXY(android.graphics.Shader.TileMode.REPEAT, android.graphics.Shader.TileMode.REPEAT);

To set it as layout background, use:

// create main panel
RelativeLayout panel = new RelativeLayout(this);
panel.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
panel.setBackgroundDrawable(bitmapDrawable);

Voila!
android_background_tile_repeat_image

Sample code is available here:
BackgroundTile

Leave a Reply