Pages

Monday 6 June 2011

Customizing the Title Bar

How do I change the title bar for my app?
Often I find that I want to remove the Android title bar from my app entirely and create my own within the layouts. To achieve this, just set the theme for the entire application, or individual activity to Theme.NoTitleBar then set my own title bar within the layouts as required:

AndroidManifest.xml
<application
  android:icon="@drawable/icon"
  android:label="@string/app_name"     
  android:theme="@android:style/Theme.NoTitleBar"
  <activity android:name=".Main" android:theme="@android:style/Theme.NoTitleBar" />

However, the standard title bar is fairly flexible in terms of background and text options (although centering the title text is not trivial). To modify it we start off by creating our own theme and, in this case, inherit from the default android theme. This theme contains system names for the android title styles and effectively overrides them. Where the name denotes a style, e.g. windowTitleStyle, a reference to a defined style is required.

/res/values/themes.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="Theme.myTheme.TitleBar" parent="android:Theme">
    <item name="android:windowTitleBackgroundStyle">@style/windowTitleBackgroundStyle</item>
    <item name="android:windowTitleStyle">@style/windowTitleStyle</item>
    <item name="android:windowTitleSize">50dip</item>
  </style>
</resources>

/res/values/styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
  <style name="windowTitleBackgroundStyle">  
    <item name="android:background">@FF000</item>                
  </style>
  <style name="windowTitleStyle">
    <item name="android:textColor">#FFFFFF</item>
    <item name="android:padding">12dip</item>
    <item name="android:textStyle">bold</item>
    <item name="android:textSize">16sp</item>
  </style>
</resources>

Finally set the theme within the manifest for either the application or individual activities...

AndroidManifest.xml
<application
  android:icon="@drawable/icon"
  android:label="@string/app_name"     
  android:theme="@style/Theme.myTheme.TitleBar" >

2 comments:

andy said...

Many Thanks. You just saved my day.

AssMan said...

thanks a lot for this

Post a Comment