默認標題欄僅支持單行文本,樣式固定單調。通過自定義標題欄可實現:自定義背景、自定義高度、嵌入按鈕/圖標/進度條等複雜佈局、動態修改內容。
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());
}
}
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE) — 啟用自定義標題特性setContentView(R.layout.main) — 設置主界面佈局getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title) — 指定標題欄佈局findViewById() 查找標題欄控件 — 必須在 setFeatureInt 之後錯誤順序會導致: 標題欄不顯示、找不到控件、Crash 等問題。
// 獲取標題欄 TextView
TextView titleText = findViewById(R.id.title_text);
titleText.setText("新標題");
// 修改背景顏色
getWindow().findViewById(android.R.id.title).setBackgroundColor(Color.RED);
ImageView btnBack = findViewById(R.id.btn_back); btnBack.setOnClickListener(v -> finish());
- 56dp
- @style/TitleBackgroundColor
- @color/colorPrimaryDark
- true
Android 5.0 推出 Toolbar 完全取代傳統標題欄,優勢:
Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true);
| API Level | 推薦方案 | 備註 |
|---|---|---|
| < 11 (3.0) | requestWindowFeature + 自定義佈局 | 本文方案 |
| 11-20 | ActionBar (原生) / Toolbar (AppCompat) | ActionBar API 引入 |
| 21+ (5.0+) | Toolbar + Material Design | 標準方案,功能最全 |
| 所有版本 | Toolbar (via AppCompat) | 統一代碼庫,推薦 |