android - 操纵工具栏的标题和其他元素

标签 android android-toolbar

我使用的是 AppCompat 工具栏,它的大部分功能都很棒。然而,处理标题一直是一场噩梦。它默认设置为应用程序名称,我找不到隐藏它的方法。

我试图隐藏它,这样我就可以添加自己的 TextView ,这样我就可以将标题文本正确地对齐到顶部,目前它是左对齐但垂直居中的。如果我不使工具栏高度比平时长,我不知道如何将它定位在正常位置。

你们是如何管理工具栏的?如何将标题文本对齐到标题通常所在的顶部位置?

编辑:我已经添加了它的外观截图。我现在试图让我的项目保密,所以我删除了所有识别元素。但请注意 D(标题)未与顶部对齐。

toolbar

最佳答案

如果您将工具栏设置为操作栏 setSupportActionBar(toolbar); 然后您可以使用

简单地禁用标题
getSupportActionBar().setDisplayShowTitleEnabled(false);

并在工具栏布局中添加一个 TextView 作为标题,因为工具栏也是一个 View 。见下文

<LinearLayout
        android:id="@+id/toolbar_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <android.support.v7.widget.Toolbar
            xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/material_blue"
            android:elevation="5dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark"
            app:theme="@style/ToolbarCustomIconColor" >

            <TextView
                android:id="@+id/textview_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center_horizontal"
                android:gravity="center"
                android:text="@string/app_name"
                android:textColor="@android:color/white" />
        </android.support.v7.widget.Toolbar>
    </LinearLayout>

这样您就可以在任何地方安排您的标题并进行相应的自定义。

关于android - 操纵工具栏的标题和其他元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28735539/

相关文章:

java - AsyncTask 在 doinbackground() 上抛出错误 "Caused by java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.Void[]"

android - MaterialSearchView 不会专注于启动 - Android

android - 如何在工具栏 Android 中使用 SearchView

Android : Error in getting id of any view created inside android. support.v7.widget.Toolbar

android - 将图像调整为正方形分辨率

java - Android 内部存储上的目录创建失败

安卓内存泄漏?位图超出 MapView 的 VM 预算错误

android - 旋转 Android ImageView 及其背景

android - 带工具栏的 SwipeRefreshLayout (v4) 隐藏 ListView

java - 向自定义工具栏添加后退按钮的最佳方法是什么?