How can I place a ProgressBar at the right of the Toolbar?

doplumi picture doplumi · Oct 22, 2014 · Viewed 18k times · Source

With the new Lollipop API, we have to use a Toolbar if we want to personalize the action bar aspect.

Adding a ProgressBar to the Toolbar is as simple as adding it to the Toolbar ViewGroup, as Chris Banes said.

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/material_green_500"
    android:minHeight="?attr/actionBarSize"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

    <!-- Color is Brown 500 -->
    <ProgressBar
        android:id="@+id/toolbar_progress_bar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:indeterminateTint="#795548"
        android:indeterminateTintMode="src_in"/>

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

But how can we place it at the right of the Toolbar, where it belongs?

The layout_gravity attribute seems to not be defined for the Toolbar. Setting it from the xml has no effect. I tried to change the width of the ProgressBar, with no success.

What do I do?

EDIT: There is a programmatical solution to this problem, see @mdelolmo reply for that.

Answer

dhiku picture dhiku · Feb 24, 2015

You can try this. It worked for me. Key here is to define layout_gravity in the xml: android:layout_gravity="right"

<android.support.v7.widget.Toolbar     
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/material_green_500"
android:minHeight="?attr/actionBarSize"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

<!-- Color is Brown 500 -->
<ProgressBar
    android:id="@+id/toolbar_progress_bar"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:indeterminateTint="#795548"
    android:indeterminateTintMode="src_in"
    android:layout_gravity="right"
/>

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