Saturday, April 7, 2012

Repeating an image as a background

Often you need to use backgrounds with textures or gradients for linearlayouts, relativelayouts or other common layouts. But by default, Android will stretch the graphic distorting it, when what you really want it to do is to tile or repeat the graphic. Tilemode is what controls this android:tileMode="repeat". Note: Like many features, there are some bug reports that it doesn't work consistently across every device, so be sure to test! To get it to repeat, you create a bitmap with the graphic you want to repeat as an xml file like below.
 <?xml version="1.0" encoding="utf-8"?>  
 <bitmap xmlns:android="http://schemas.android.com/apk/res/android"  
   android:src="@drawable/practice_backgroundtab"   
   android:tileMode="repeat" />  
Then in the linear layout you can specify the background like normal
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
   android:layout_width="fill_parent"  
   android:layout_height="wrap_content"  
   android:orientation="horizontal"  
   android:background="@drawable/practicebackrepeat"  
   android:gravity="center_horizontal" >