MattsBits
MattsBits

MattsBits

Setting the Background Colour of a TextView  

by Matt Hawkins, 21/07/2011
Categories : Android

The following methods show how you can set the background colour of a TextView object when developing Android applications using the SDK.

There are two ways to change the background colour.

Method 1

Simply use setBackgroundColor to specify a colour directly.


TextView tv = new TextView(activity);
tv.setBackgroundColor(0xffff0000);


Please note that 0xff is the transparency setting. ff0000 is the colour. In this case Red.

Method 2

First create an XML file in your res/values folder. The name isn't important but colours.xml will do for now. Insert the following text :


<resources>
<color name="white">#ffffffff</color>
<color name="black">#ff000000</color>
<color name="red">#ffff0000</color>
<color name="green">#ff00ff00</color>
<color name="blue">#ff0000ff</color>
</resources>

This defines some preset colours. Please note that the first two characters are related to transparency and the last size define the colour. Feel free to add other colours as required.

You can then use setBackgroundResource to set the colour to one of these predefined colours.


TextView tv = new TextView(activity);
tv.setBackgroundResource(R.color.red);

Author : Matt Hawkins  Last Edit By : Matt Hawkins
PHP Powered  MySQL Powered  Valid XHTML 1.0  Valid CSS  Firefox - Take Back The Web  EUKHost - Recommended Webhosting Solutions

MattHawkins CMS v3.0 - Copyright 2009-2022