如何更改工具栏子视图的对齐方式

Jon*_*Jon 15 android android-layout android-toolbar

我有一个工具栏,我想ImageView在xml中添加一个布局.我希望它对齐,而不是默认左对齐.

根据文件:

应用程序可能会向工具栏添加任意子视图.它们将出现在布局中的这个位置.如果子视图的Toolbar.LayoutParams指示CENTER_HORIZONTAL的重力值,则在测量完所有其他元素后,视图将尝试以工具栏中剩余的可用空间为中心.

但我不能把重心放在任何东西上.

我的布局

<android.support.v7.widget.Toolbar
    style="@style/ToolbarStyle"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize">

    <ImageView
        android:id="@+id/bluetoothState"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_bluetooth_status_white"
        android:contentDescription="@string/content_description_bluetooth_status"
        android:padding="8dp"/>
</android.support.v7.widget.Toolbar>
Run Code Online (Sandbox Code Playgroud)

默认对齐

Jon*_*Jon 39

android:layout_gravity="right"是答案.哪个问题链接的文档甚至暗示.(它提到了引力,但没有以特定的xml属性方式提到)

无论如何,问题是Android Studio并没有真正建议自定义视图的属性.这包括android.support.v7.widget.Toolbar." 设计"选项卡不会将layout_gravity列为属性,如果在文本选项卡上键入它,则不会自动完成它.

下面的完整示例代码..

<android.support.v7.widget.Toolbar
    style="@style/ToolbarStyle"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize">

    <ImageView
        android:id="@+id/bluetoothState"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/ic_bluetooth_status_white"
        android:contentDescription="@string/content_description_bluetooth_status"
        android:padding="8dp"
        android:layout_gravity="right"/>

</android.support.v7.widget.Toolbar>
Run Code Online (Sandbox Code Playgroud)