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.
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:
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);

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));


Sample code is available here:

Leave a Reply