Saturday, January 24, 2009

How to have a tiled background

Today, I wanted to have a tiled background in my activity.
Until now, my android application only had a stretched image, so I though it was a good time for a change !

Having a background pattern that repeat itself seems like a very common idea, in particular on mobile development where you do not want to spend too much memory on a big image !



But actually it took much more time that I would have think to find this one !
I finally came up with this code :



public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main_menu);
View MainLayoutView = (View) findViewById(R.id.MainLayout);
BitmapDrawable MyTiledBG = new BitmapDrawable( BitmapFactory.decodeResource(getResources(), R.drawable.background) );
MyTiledBG.setTileModeXY( Shader.TileMode.REPEAT , Shader.TileMode.REPEAT );
MainLayoutView.setBackgroundDrawable( MyTiledBG );
<...>
}
(note that you can use also Shader.TileMode.MIRROR to have a different repeatition pattern )

This code works fine, but I would have prefered a XML way to do this.

I've seen the BitmapDrawable attribute defined in the SDK, but couldn't come with anything working...

2 comments:

Anonymous said...

What is R.drawable.background? Where do I choose a path for the image?

Kyla Curtis said...

Helllo nice blog