Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Change the Alignment of Toolbar Child Views

I have a toolbar and I want to add an ImageView to its layout in xml. I want it to align right, instead of the default align left.

According to the documentation:

The application may add arbitrary child views to the Toolbar. They will appear at this position within the layout. If a child view's Toolbar.LayoutParams indicates a Gravity value of CENTER_HORIZONTAL the view will attempt to center within the available space remaining in the Toolbar after all other elements have been measured.

But I can't set the gravity on anything.

My Layout

<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>

Default Alignment

like image 424
Jon Avatar asked Jun 11 '15 19:06

Jon


1 Answers

android:layout_gravity="right" is the answer. Which the documentation the question links too even suggests. (well it mentions gravity, but not in the particular xml attribute way needed)

Anyway, the issue was Android Studio doesn't really suggest attributes for custom views. This includes android.support.v7.widget.Toolbar. The Design tab won't list layout_gravity as an attribute and it won't auto complete it if you type it on the text tab.

Full example code below..

<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>
like image 145
Jon Avatar answered Oct 22 '22 16:10

Jon