Android 开发如何将 Action Bar 标题设置为居中对齐
实现ActionBar标题居中的几种可行方案
方案1:自定义ActionBar布局(推荐,兼容性最优)
是目前适配性最高、自定义灵活度最好的实现方式,完全不会受系统版本和默认主题影响。
步骤1:创建自定义标题布局文件
在res/layout目录下新建custom_actionbar_title.xml,内容如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="wrap_content" android:paddingRight="?attr/actionBarSize" android:orientation="vertical"> <TextView android:id="@+id/actionbar_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Settings" android:textColor="@android:color/white" android:textSize="18sp" android:textStyle="bold" android:layout_gravity="center" /> </LinearLayout>
注:根布局的paddingRight属性用于抵消左侧返回键的宽度占位,保证标题视觉完全居中
步骤2:在onCreate中应用自定义布局
替换你原有逻辑为如下代码即可:
ActionBar actionBar = Objects.requireNonNull(getSupportActionBar()); // 开启自定义布局权限 actionBar.setDisplayShowCustomEnabled(true); // 隐藏默认自带的标题 actionBar.setDisplayShowTitleEnabled(false); // 保留左上角返回键 actionBar.setDisplayHomeAsUpEnabled(true); // 加载自定义布局 LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE); View customView = inflater.inflate(R.layout.custom_actionbar_title, null); // 如果需要动态修改标题,可通过如下代码操作 // TextView titleTv = customView.findViewById(R.id.actionbar_title); // titleTv.setText("自定义标题内容"); actionBar.setCustomView(customView);
方案2:直接修改默认标题属性(适合不想新建布局的场景)
如果不想新增布局文件,可以通过遍历View树找到ActionBar自带的标题TextView,修改对齐属性,缺点是不同系统版本的ActionBar结构可能有差异,兼容性略差:
Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); setTitle(Html.fromHtml("<font color=\"white\">" + "Settings" + "</font>")); // 遍历找到标题TextView并修改对齐属性 Toolbar actionBarView = getWindow().getDecorView().findViewById(androidx.appcompat.R.id.action_bar); for (int i = 0; i < actionBarView.getChildCount(); i++) { View child = actionBarView.getChildAt(i); if (child instanceof TextView) { TextView titleTv = (TextView) child; if (titleTv.getText().equals(getTitle())) { titleTv.setGravity(Gravity.CENTER); Toolbar.LayoutParams params = (Toolbar.LayoutParams) titleTv.getLayoutParams(); params.width = Toolbar.LayoutParams.MATCH_PARENT; params.rightMargin = getResources().getDimensionPixelSize(androidx.appcompat.R.dimen.abc_action_bar_default_height_material); titleTv.setLayoutParams(params); break; } } }
补充建议
目前原生ActionBar已被官方废弃,推荐直接使用Toolbar组件替换,组件本身支持高度自定义,居中、修改样式等操作更简单,后续迭代维护成本更低。
内容的提问来源于stack exchange,提问作者Senith Umesha
相关产品推荐
相关产品推荐

