android - Android如何将顶部actionBar的标题居中?
问题描述
开始我的目标是使我的标题居中。我通过选择底部导航活动模板开始了一个项目。这带有 3 个片段和一个主要活动。我正在尝试将顶部操作栏的标题居中。我试图通过 id 访问 mobile_navigation 并在 MainActivity 中对齐文本,但这似乎不起作用。我还尝试在 homeFragment.xml 中添加一个 textAlignment 属性,但这也不起作用。我没有找到任何类似的情况,任何人都知道我该如何解决这个问题?
mobile_navigation.xml:
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/mobile_navigation"
app:startDestination="@+id/navigation_home">
<fragment
android:id="@+id/navigation_home"
android:name="com.Example.exmaple.ui.home.HomeFragment"
android:label="@string/app_name"
tools:layout="@layout/fragment_home" />
<fragment
android:id="@+id/navigation_dashboard"
android:name="com.Example.exmaple.ui.dashboard.DashboardFragment"
android:label="@string/title_dashboard"
tools:layout="@layout/fragment_dashboard" />
<fragment
android:id="@+id/navigation_notifications"
android:name="com.Example.exmaple.ui.notifications.NotificationsFragment"
android:label="@string/title_notifications"
tools:layout="@layout/fragment_notifications" />
</navigation>
我还尝试添加:
android:gravity="center"
欢迎任何反馈。
解决方案
要在您的所有内容中使用自定义标题,您Toolbar
只需记住这Toolbar
只是一个精美的 ViewGroup,因此您可以像这样添加自定义标题:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_top"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="@color/action_bar_bkgnd"
app:theme="@style/ToolBarTheme" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Toolbar Title"
android:layout_gravity="center"
android:id="@+id/toolbar_title" />
</android.support.v7.widget.Toolbar>
这意味着您可以随意设置样式,TextView
因为它只是一个常规的TextView
. 因此,在您的活动中,您可以像这样访问标题:
Toolbar toolbarTop = (Toolbar) findViewById(R.id.toolbar_top);
TextView mTitle = (TextView) toolbarTop.findViewById(R.id.toolbar_title);
setSupportActionBar(toolbar);
mTitle.setText(toolbar.getTitle());
getSupportActionBar().setDisplayShowTitleEnabled(false);
推荐阅读
- node.js - 如何获取仅具有 _id 的新创建评论,而不是所有评论的所有帖子。请参阅描述以获取详细信息
- python - 在 Pandas 数据框列上应用条件
- android - Gradle Sync 需要很多时间
- swift - 无法将“[String:Any]”类型的值转换为预期的参数类型“Data”Alamofire - 可编码
- c++ - 标准::地图
operator[] 需要使用空构造函数创建 A - excel - 在一页上打印长电子表格(Excel 到 PDF)
- java - 如何创建具有特定名称的文件
- excel - 无法单击指向 https://www.asic.gov.au 的超链接
- regex - 尝试加载字体时,AWS Amplify 返回错误 403
- jenkins - Jenkins中JiraTestResultReporter插件配置的404问题