Search code examples
androidxmlandroid-layoutandroid-toolbarandroid-appbarlayout

How to correctly align buttons in an action bar with a navigation view


I created a action bar with two buttons . This activity also included with a side menu . I used a navigation view for that purpose.

So , my activity looks like below,

enter image description here

But actually I want it like below (notice the "Cancel" button is more closer to navigation bar, and both buttons are properly aligned),

enter image description here

This this is my action bar code(in layout file),

<android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar_target_ranges"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/AppTheme.PopupOverlay">

            <LinearLayout
                android:id="@+id/target_ranges_layout_main"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal">

                <android.support.v7.widget.AppCompatButton
                    android:id="@+id/target_ranges_cancel_btn"
                    style="@style/ButtonStyle_Med"
                    android:layout_weight="1"
                    android:text="@string/action_cancel" />

                <android.support.v7.widget.AppCompatButton
                    android:id="@+id/target_ranges_save_btn"
                    style="@style/ButtonStyle_Med"
                    android:layout_weight="1"
                    android:text="@string/action_save" />

            </LinearLayout>

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

</android.support.design.widget.AppBarLayout>

How to achieve this ? Have any ideas ?


Solution

  • The problem is that your Toolbar does not set center gravity for the inner LinearLayout. You can do that by setting LayoutParams to the LinearLayout like this:

        Toolbar toolbar = (Toolbar) findViewById(R.id. toolbar_target_ranges);
    
        LinearLayout toolbarRow = (LinearLayout) toolbar.findViewById(R.id. target_ranges_layout_main);
    
        toolbarRow.setLayoutParams(new Toolbar.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER));