萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> Android 開發

Android 自定義標題欄開發完整指南:佈局、樣式與代碼實現

需求背景

默認標題欄僅支持單行文本,樣式固定單調。通過自定義標題欄可實現:自定義背景、自定義高度、嵌入按鈕/圖標/進度條等複雜佈局、動態修改內容。

實現三步驟

步驟 1:定義標題欄佈局 (res/layout/title.xml)




    

    

步驟 2:定義標題欄樣式 (res/values/titlestyle.xml)



    
    

    
    

步驟 3:應用主題與代碼設置 (AndroidManifest.xml + Activity)



    
public class MyTitleActivity extends Activity {
    private Button titleButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        // 關鍵:必須在 setContentView 之前調用
        requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
        setContentView(R.layout.main);
        
        // 關鍵:設置自定義佈局作為標題欄
        getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
        
        // 查找標題欄中的控件(需在 setFeatureInt 之後)
        titleButton = findViewById(R.id.title_button);
        titleButton.setOnClickListener(v -> 
            Toast.makeText(this, "Clicked!", Toast.LENGTH_SHORT).show());
    }
}

關鍵順序說明(不可調換)

  1. requestWindowFeature(Window.FEATURE_CUSTOM_TITLE) — 啟用自定義標題特性
  2. setContentView(R.layout.main) — 設置主界面佈局
  3. getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title) — 指定標題欄佈局
  4. findViewById() 查找標題欄控件 — 必須在 setFeatureInt 之後

錯誤順序會導致: 標題欄不顯示、找不到控件、Crash 等問題。

進階技巧

1. 動態修改標題欄內容

// 獲取標題欄 TextView
TextView titleText = findViewById(R.id.title_text);
titleText.setText("新標題");

// 修改背景顏色
getWindow().findViewById(android.R.id.title).setBackgroundColor(Color.RED);

2. 標題欄添加返回按鈕


ImageView btnBack = findViewById(R.id.btn_back);
btnBack.setOnClickListener(v -> finish());

3. 沉浸式狀態欄配合 (Android 5.0+)

    56dp 
    @style/TitleBackgroundColor
    @color/colorPrimaryDark
    true

4. Toolbar 替代方案 (現代推薦)

Android 5.0 推出 Toolbar 完全取代傳統標題欄,優勢:

  • 可放置佈局任意位置,不限於頂部
  • 支持菜單、導航圖標、標題、副標題、Logo
  • 可動畫隱藏/顯示、收縮/展開 (CollapsingToolbarLayout)
  • 符合 Material Design 規範
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);

版本兼容性總結

API Level推薦方案備註
< 11 (3.0)requestWindowFeature + 自定義佈局本文方案
11-20ActionBar (原生) / Toolbar (AppCompat)ActionBar API 引入
21+ (5.0+)Toolbar + Material Design標準方案,功能最全
所有版本Toolbar (via AppCompat)統一代碼庫,推薦
copyright © 萬盛學電腦網 all rights reserved