Instead of using the pre-made Android GUI elements you can create your own drawables in XML. There’s some documentation on the Android documentation website, but it is not very detailed. Let’s say you want to create a drawable called “tile”, which works similar to a button, but has a toggle state, that is, it remains in either state until it is clicked again. The first thing you do is create an XML file called “tile.xml” in the “res/drawable” directory:

<?xml version=“1.0” encoding=“utf-8”?>
<selector xmlns:android=“http://schemas.android.com/apk/res/android"> <item android:drawable=“@drawable/tile_pressed” android:state_pressed=“true”/>
<item android:drawable=“@drawable/tile_pressed” android:state_selected=“true”/>
<item android:drawable=“@drawable/tile_normal”/>
</selector>

This code refers to two other drawables “tile_pressed” and “tile_normal” that are to be defined soon. Please note, that the “tile_pressed drawable” is used for two possible states “pressed” and “selected”.

The “tile_normal” drawable is consequently defined in the file “res/drawable/tile_normal.xml” and looks quite simple. It just defines a shape, in that case a rectangle, and a color:

<?xml version=“1.0” encoding=“utf-8”?>
<shape xmlns:android=“
http://schemas.android.com/apk/res/android" android:shape=“rectangle” >
<solid android:color=”#999999” ></solid>
</shape>

The same goes for the “tile_pressed” tile, only in a different color:

<?xml version=“1.0” encoding=“utf-8”?>
<shape xmlns:android=“
http://schemas.android.com/apk/res/android" android:shape=“rectangle”>
<solid android:color=”#F5A503”></solid>
</shape>

Now you can use the tile as a background in the “layout.xml” file where it will act according to the events the button receives:

<Button android:id=“@+id/Button00” android:layout_width=“50dp”
android:layout_height=“50dp” android:text=“” android:background=“@drawable/tile” />

To implement the toggle function you use the setSelected() instance method of the button in the click event handler:

View.OnClickListener buttonClicked = new View.OnClickListener() {
public void onClick(View v) {
v.setSelected(true);
….