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.
<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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With