首页 > 解决方案 > 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"

欢迎任何反馈。

标签: androidandroid-layoutandroid-fragments

解决方案


要在您的所有内容中使用自定义标题,您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);

推荐阅读