Archive for the ‘android’ Category

How To Make A Custom Window Title With Android

When you start making Android apps that ship to clients and paying customers, chances are you will find the default Android window title lacking. The default title displays the name of your app on top of a very neutral-looking grey background.

The default Android window title

While OK for experimental and side projects the stock grey colour will likely not mix well with the colour theme of your app, especially if you are using colours other than black, white and grey.

Here is how you make a custom window title. First you need to create a layout XML file and put in the res/layout directory of your Android project:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/title_bar"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
  	android:gravity="center_vertical"
  	android:background="#77b48e"
    >

   	<TextView
   	    android:id="@+id/title_bar_viewname"
        android:layout_width="wrap_content"
  		android:layout_height="wrap_content"
  		android:text="My Custom Title Here"
  		android:textColor="@android:color/white"
  	/>
</LinearLayout>

Now you have to tell Android to apply the custom title layout that you have created. In order to do that you need to request that your activity be given the FEATURE_CUSTOM_TITLE window feature:

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.activity_main);
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title_bar_example);
.
.
.
    }

Make sure that the call to setContentView() occurs after requestWindowFeature() and before setFetureInt()

You would think that this is enough, however when you run the code you will see that there is still a remnant of the old stock background still lurking underneath our fresh new custom title. Still no go!

Custom Android title step 1: pesky grey still remains

In order to get rid of the last remaining traces of the stock grey we need to resort to a bit of Android wizzardy:

int titleContainerId = (Integer) Class.forName(
        "com.android.internal.R$id").getField("title_container").get(null);

ViewGroup vg = ((ViewGroup) getWindow().findViewById(titleContainerId));
if(vg != null){
	vg.setPadding(0, 0, 0, 0);
}

The trick here is to get a runtime reference to the title_container in a way that doesn’t break between Android releases and to set its padding to 0. And here is the final result:

android, title

Your custom Android title is now complete

And from here you can go ahead and add whatever other images and controls you need by adding them by adding them to the layout file.