Friday, May 8, 2015

Adding custom title bar to the theme in android


I was developing a quiz app for a customer. And the requirement was to have a custom header/title for the application. That’s also horizontally center aligned to the display.



In Android, you can set your custom title to the theme.  It’s pretty simple. I will take the quiz example itself to demonstrate this. You just create an Android project called as "Quiz". Now for this project, for each screen we want to create the title as “M-Quiz”. 
Here I am not going to discuss about the code related to quiz But we are going to discuss about how to add the custom title bar for this application.



First you need to add the below code to the styles.xml in res/values folder. If this file is not there, you can create one.



























Now we need to add the colors we are going to use in our application. Create colors.xml file in the res/values folder. Add colors, that are needed for the application.



The colors.xml file contains the following code:



















 



































Add themes.xml file in the res/values folder. 
themes.xml file contains the following code:  































The created style should be added into the theme file. After creating these files open android manifest file and apply the theme into the whole application or an activity.

manifest file code :







Create a layout for the custom title bar. The layout can contain any android controls. You can add even the logo of the application, any images, or any controls as well. In the below layout code, I am just adding the text. No other controls and no images. If you want you can add them. I created a layout header.xml with the below code in it:













Now at last we need to add the following code to the oncreate() method of the activity.


 
 










Now you can run the application and check. You can see the customized title bar on top as below :
























That’s it. Happy Coding...

If you forget any of the steps above, you may get the below force closed. You can see this error in the logcat:


Caused by: android.util.AndroidRuntimeException: You cannot combine custom titles with other title features
 
To fix this issue, you need to add below line in themes.xml
name="android:windowNoTitle">true


or in the AndroidManifest.xml, you need to remove the below code for that perticular activity


android:theme="@android:style/Theme.Black.NoTitleBar"


And you need to add the code in mainactivity.java or wherever you want the cusom window title to be displayed:



No comments: