Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 自訂標題欄背景圖的完整實作教學

編輯:關於 Android 程式設計

想讓 App 的標題欄更有質感?除了單純的純色背景,我們還可以為標題欄設定具有凹凸感的背景圖片。本文將一步步示範如何自訂標題欄背景。

設定標題欄背景

1> 準備背景圖片 background_pix.png

註:用背景圖片比單純用顏色的好處,是可以讓背景看起來有凹凸的層次感。

2> 在 drawable 文件夾下放 XML 檔案

bitmap_repeat.xml

 <?xml version="1.0" encoding="utf-8"?> <bitmap xmlns:android="https://schemas.android.com/apk/res/android" android:src="@drawable/title_pic" android:tileMode="repeat"> </bitmap> 

3> 定義樣式檔案 style.xml

 <?xml version="1.0" encoding="utf-8"?> <resources> <!-- 自定義標題樣式 --> <style name="StatusBarBackground"> <item name="android:background">@drawable/bitmap_repeat </item> </style> <style name="XTheme" parent="android:Theme"> <!-- Window attributes --> <item name="android:windowTitleBackgroundStyle">@style/StatusBarBackground </item> </style> <!-- 自定義標題樣式 --> </resources> 

4> 在 manifest.xml 中引用主題 android:theme="@style/XTheme"

 <activity android:name=".activity.MainActivty" android:screenOrientation="portrait" android:configChanges="keyboardHidden|orientation" android:theme="@style/XTheme"> </activity> 

如果你想要更靈活地自訂標題欄布局,可以建立一個自訂標題欄的 layout 檔案 ct_title.xml。注意:若在 ct_title.xml 中直接用 android:background="@drawable/bitmap_repeat" 來設定標題欄背景,會出現填充不滿的效果,因此建議改用上面的主題樣式方式。接著在 Activity 中引用:

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

透過主題樣式 + 自訂標題欄布局的組合,你就能打造出具個人風格、且能正確鋪滿背景的標題欄了。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved