android - 工具栏将标题与后退按钮居中对齐

标签 android android-actionbar android-xml android-toolbar

我正在我的应用程序中添加 Toolbar,但我似乎遇到了问题。在应用程序中,我应该在屏幕右侧有一个按钮,标题在中间。但是当我深入应用程序时,我应该通过执行 getSupportActionBar().setDisplayHomeAsUpEnabled() 在左侧显示后退箭头。这工作正常,但是当我添加后退按钮时,文本向右移动,所以我猜后退按钮可以有一些空间。谁能告诉我如何让我的按钮在右边,标题总是在中间,不管后退按钮是否显示?

这是我的工具栏 xml 布局代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/white"
    android:padding="5dp"
    tools:ignore="MissingPrefix">

    <RelativeLayout
        android:id="@+id/toolbar_info_holder"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/toolbar_title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:gravity="center"
            android:textColor="@color/actionbar_title_color" />

        <ImageView
            android:id="@+id/toolbar_image"
            android:layout_width="40dp"
            android:layout_height="40dp"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true" />

        <TextView
            android:id="@+id/toolbar_count"
            android:layout_width="13dp"
            android:layout_height="13dp"
            android:layout_alignParentRight="true"
            android:layout_alignParentTop="true"
            android:background="@drawable/red_circle"
            android:gravity="center"
            android:text="4"
            android:textColor="@color/white"
            android:textSize="9sp" />
    </RelativeLayout>

</android.support.v7.widget.Toolbar>

最佳答案

对我有用的是设置:

android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"

到工具栏的 subview ,它对我来说是一个 LinearLayout(对你来说是一个 RelativeLayout)。一开始我觉得这很奇怪,但它确实有效,所以我不会提示。

关于android - 工具栏将标题与后退按钮居中对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35338388/

相关文章:

android - 不要导航到 WebView 中的其他页面,禁用链接和引用

android - 在保持 android :targetSdkVersion to be 14 的同时在 ICS 上显示菜单按钮

android - TabLayout 上方的页眉布局

android - 使用 DDMS 模拟器控件将欺骗位置发送到平板电脑 android 设备

android - Presenter/View/ViewState 关系

android - Gradle 无法通过企业代理连接到 maven repo - 需要通过 Sencha/Cordova 进行配置

android - 具有 AppCompat 的透明覆盖 ActionBar?

android - 在 Android 上使用下拉导航模式旋转设备时如何保留/恢复 fragment 实例?

android - 如何在android中制作椭圆形按钮?