Monday, February 4, 2013

Custom Title Bar in Android

For Adding custom Title Bar in Android you should have:

  • Default title bar enabled.
  • Create res->layout->custom_title.xml
  • Adding Code to Activity.
If you are disabled default title bar for adding custom title then this will not work. Activity throws AndroidRuntimeException (You cannot combine custom titles with other title features) so enable Default title bar.

Create custom_title.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/RelativeLayout1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:scaleType="fitXY"
        android:src="@drawable/image_title" />

</RelativeLayout>

Add the Following Code to activity:

@Override
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);  
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
}

Also you can set title-bar size by adding following line in res->values->styles.xml:

<resources>

    <style name="AppTheme" parent="android:Theme.Black">
        <item name="android:windowTitleSize">35dip</item>
        <item name="android:windowTitleBackgroundStyle">@style/CustomTitleBarBackground</item>
    </style>

    <style name="CustomTitleBarBackground">
        <item name="android:background">#323331</item>
    </style>

</resources>

 And in manifest:

<application
         android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <uses-library android:name="com.google.android.maps" />

        <activity android:name=".Activity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
</application>


That's all Now your activity contains custom title bar.Later you can add/design as per your application requirement.

Reference: How to Create Custom Window Title in Android

No comments:

Post a Comment