Monday, October 24, 2011

Custom Titlebar in Android

Inorder to create your custom titlebar you just need to create theme like layout files and set custom title in in java file thats it. let do it quickly, first you need to create a mytitle.xml file in layout with following code.which contains image to be shown in title with text or you can design it yourself. 



<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="fill_parent" 
  android:layout_height="20px"
  
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
  android:layout_width="wrap_content" android:layout_height="wrap_content"
  android:orientation="vertical"
  android:paddingTop="4sp"
      android:paddingLeft="5sp"
   >
 <ImageView 
xmlns:android="http://schemas.android.com/apk/res/android" 
 android:layout_width="16px" 
  android:layout_height="16px" 
  android:src="@drawable/zoom"
/>
</LinearLayout>

<TextView 
  xmlns:android="http://schemas.android.com/apk/res/android" 
  android:id="@+id/myTitle" 
  android:text="This is my new title" 
  android:layout_width="fill_parent" 
  android:layout_height="fill_parent" 
  android:textColor="@color/titletextcolor"
  android:layout_marginLeft="25px"
   android:paddingTop="3px" 
   /> 
   
</RelativeLayout>
Then create themes.xml file in values folder and write following.in which we have created customtheme setting title bar background color. 



<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <style name="customTheme" parent="android:Theme">  
        <item name="android:windowTitleBackgroundStyle">@style/WindowTitleBackground</item>    
    </style>  
</resources>
Then styles.xml with following code 

<?xml version="1.0" encoding="utf-8"?> 
<resources>  
   <style name="WindowTitleBackground">      
        <item name="android:background">@color/titlebackgroundcolor</item>                    
    </style> 
</resources>
colors.xml in same folder to to set title text and background color. 

<?xml version="1.0" encoding="utf-8"?> 
<resources>    
    <color name="titlebackgroundcolor">#ff6a00</color> 
    <color name="titletextcolor">#FFFF00</color> 
</resources>
an entry in manifest file to point out the activity or application using customtheme that you have created. 

<activity android:name=".CustomTitleBar"
               android:label="@string/app_name" 
               android:theme="@style/customTheme"
               >
and last step at the top of your activity write following lines of code. 

requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); 
     setContentView(R.layout.main);  // or what ever layout you using
     getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.mytitle);

No comments:

Post a Comment