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 a "Quiz". Now for this
project, for each screen, we want to create the title as “M-Quiz”.
Here I am not
going to discuss the code related to the 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 the 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 a 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 to the theme file.
After creating these files
open the android manifest file and apply the theme to the whole application or 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 create() 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 log:
To fix this issue, you need to add the below line in themes.xml
- name="android:windowNoTitle">true
or in the AndroidManifest.xml, you need to remove the below code for that particular activity
android:theme="@android:style/Theme.Black.NoTitleBar"
And you need to add the code in mainactivity.java or wherever you want the custom window title to be displayed:
If you forget any of the steps above, you may get the below force closed. You can see this error in the log:
Caused by: android.uti l.AndroidRuntimeException:
You cannot combine custom titles with other title features
To fix this issue, you need to add the below line in themes.xml
or in the AndroidManifest.xml, you need to remove the below code for that particular activity
android:theme="@android:style/Theme.Black.NoTitleBar"
And you need to add the code in mainactivity.java or wherever you want the custom window title to be displayed:
No comments:
Post a Comment