Two methods for customizing header bar styles in Android

  • 2020-06-01 11:00:00
  • OfStack

The color matching of the original Android title bar is monotonous, just like black one tuo. Now suppose that your software needs to add title bar alone, which is not only beautiful but also can add progress bar. How to achieve it?

Method 1. Add the following code to your Activity onCreate method:


requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);   
setContentView(R.layout.main);  // software activity The layout of the  
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.titlebar); //titlebar Layout for your title bar 

But there is a new problem, it is not deep customization of the title bar, such as the original height and background have not changed, that there is a good way? The answer is yes,

Method 2:

So define 1 style first. If you want to modify the background, please modify android:windowTitleBackgroundStyle
If you change the height of the title bar, modify android:windowTitleSize

Example:


<?xml version="1.0" encoding="utf-8"?> 
<resources xmlns:android="http://schemas.android.com/apk/res/android"> 
 
 
<style name="CustomWindowTitleBackground"> 
    <item name="android:background">#565656</item> 
</style> 
 
 
<style name="test" parent="android:Theme"> 
   <item name="android:windowTitleSize">50dp</item> 
   <item name="android:windowTitleBackgroundStyle">@style/CustomWindowTitleBackground</item> 
</style> 
</resources>

Add the property android:theme = "@style /test" to the android_manifest.xml of the program corresponding to activity, android:theme =" @style /test"


<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
   package="com.guardian" 
   android:versionCode="1" 
   android:versionName="1.0"> 
  <application android:icon="@drawable/icon" android:label="@string/app_name" > 
    <activity android:name=".Test" 
         android:label="@string/app_name" 
         android:theme = "@style/test"  // Here is the  
         > 
      <intent-filter> 
        <action android:name="android.intent.action.MAIN" /> 
        <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
    </activity> 
 
  </application> 
  <uses-sdk android:minSdkVersion="4" /> 
 
</manifest>

You can then customize the title bar layout by setting a custom title bar xml file


Related articles: