Android Java中如何将Toolbar标题设置为居中?
解决Toolbar标题居中的几种实用方法
嘿,这个问题我之前也踩过坑!要把Toolbar的默认标题从左侧移到居中,这里有几种靠谱的实现方式,你可以根据自己的需求选:
方法一:自定义Toolbar布局(推荐,最灵活稳定)
这种方式是直接自己定义Toolbar的内部结构,完全掌控标题的位置,也是我最常用的方法:
- 首先创建一个自定义的Toolbar布局文件,比如
res/layout/layout_custom_toolbar.xml:
<?xml version="1.0" encoding="utf-8"?> <Toolbar xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/gen_toolbar_pln" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:elevation="4dp"> <!-- 自定义居中标题 --> <TextView android:id="@+id/tv_toolbar_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:text="@string/title_General" android:textColor="@android:color/white" android:textSize="18sp" android:textStyle="bold" /> </Toolbar>
- 在你的Activity布局里引用这个自定义Toolbar(替换原来的Toolbar),然后在Activity代码里这样处理:
Toolbar toolbar = findViewById(R.id.gen_toolbar_pln); setSupportActionBar(toolbar); // 一定要隐藏系统默认的标题,避免和自定义标题重复 getSupportActionBar().setDisplayShowTitleEnabled(false); // 如果需要动态修改标题,直接操作自定义的TextView即可 TextView toolbarTitle = findViewById(R.id.tv_toolbar_title); toolbarTitle.setText(R.string.title_General);
这种方法的好处是,不管你后面要给Toolbar加返回按钮、右侧菜单,都不会影响标题的居中效果,完全可控。
方法二:动态修改默认标题的位置(无需改布局,适合快速实现)
如果不想动布局文件,也可以通过代码找到Toolbar里的默认标题TextView,然后修改它的布局参数让它居中:
Toolbar toolbar = findViewById(R.id.gen_toolbar_pln); setSupportActionBar(toolbar); toolbar.setTitle(R.string.title_General); // 遍历Toolbar的子View,找到默认的标题TextView TextView defaultTitle = null; for (int i = 0; i < toolbar.getChildCount(); i++) { View child = toolbar.getChildAt(i); if (child instanceof TextView) { defaultTitle = (TextView) child; // 验证是不是标题(可以通过文字或者字体大小判断,不同主题可能有差异) if (defaultTitle.getText().toString().equals(getString(R.string.title_General))) { break; } } } if (defaultTitle != null) { // 设置标题居中 Toolbar.LayoutParams params = (Toolbar.LayoutParams) defaultTitle.getLayoutParams(); params.gravity = Gravity.CENTER; defaultTitle.setLayoutParams(params); }
⚠️ 注意:这种方法可能受Android版本、主题的影响,比如有些主题下默认标题的TextView可能有特殊的id或者嵌套结构,稳定性不如自定义布局。
方法三:简单粗暴的全局设置(仅适合无其他控件的Toolbar)
如果你的Toolbar上没有返回箭头、右侧按钮等其他控件,可以直接给Toolbar设置android:gravity="center",然后设置标题:
在布局文件的Toolbar标签里添加:
android:gravity="center"
然后代码里正常设置标题即可:
Toolbar toolbar = findViewById(R.id.gen_toolbar_pln); setSupportActionBar(toolbar); toolbar.setTitle(R.string.title_General);
不过如果后面加了其他控件,这个方法会导致所有控件都居中,所以只适合纯标题的Toolbar。
内容的提问来源于stack exchange,提问作者vishnu
相关产品推荐
相关产品推荐

