You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何居中Android应用标签,是否可以使用ActionBar实现?

实现方案说明

不推荐使用原生默认ActionBar实现标题居中,原生ActionBar定制自由度极低,Android官方目前也更推荐使用Toolbar组件替代ActionBar实现顶部导航栏需求,自定义程度更高,也更容易实现标题居中效果,你现有配置无需修改AndroidManifest.xml和strings.xml,只需按以下步骤操作即可:

  1. 关闭应用主题的默认ActionBar
    打开res/values/themes.xml找到你的Theme.TurboMileage主题,将父主题修改为不带ActionBar的Material主题,示例:
    <style name="Theme.TurboMileage" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- 原有其他主题配置保持不变 -->
    </style>
    
  2. 在Activity布局中添加自定义Toolbar
    打开MainActivity对应的布局文件(一般为activity_main.xml),添加Toolbar控件,内部嵌入居中的标题TextView:
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp">
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:textColor="@android:color/white"
            android:textSize="18sp"
            android:layout_gravity="center"/>
    
    </androidx.appcompat.widget.Toolbar>
    
  3. Activity中关联Toolbar
    在MainActivity的onCreate方法中添加如下代码,将自定义Toolbar设置为页面导航栏,同时隐藏系统默认标题:
    // Kotlin 实现
    val toolbar = findViewById<Toolbar>(R.id.toolbar)
    setSupportActionBar(toolbar)
    supportActionBar?.setDisplayShowTitleEnabled(false)
    
    // Java 实现
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayShowTitleEnabled(false);
    }
    

可选替代方案(不推荐)

如果坚持使用原有ActionBar实现居中,也可以通过自定义ActionBar视图的方式实现,代码如下:

supportActionBar?.apply {
    displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM
    setCustomView(R.layout.custom_actionbar_title)
}

其中custom_actionbar_title为仅包含居中TextView的布局文件,该方案适配不同系统版本时容易出现样式异常,稳定性不如Toolbar方案。

内容的提问来源于stack exchange,提问作者JGreen5278

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 14:09:00