Android Action Bar In A Dialog Using ToolBar - Truiton
Skip to content

Android Action Bar In A Dialog Using ToolBar

Android Action Bar In A Dialog

Android Toolbar widget is one of the new UI components available in AppCompat v21. This widget works just like an ActionBar, the only difference is, it can be placed any where on screen. The Android Toolbar widget can also be used to replace the original ActionBar in your Activity. This feature will open many new possibilities in your application. Like you can place multiple action bars on a screen, place action bars / toolbars with some specific dimensions- not covering the whole width of the screen. Also it solves one of the major issue that I faced during development, i.e. placing an Android action bar in a dialog fragment. Now with Android’s ToolBar widget this can be done very easily.

Android Toolbar widget supports a logo image, a title and a subtitle. It also supports a navigation button, custom views and more importantly an action menu. Now the question is how to display an action bar in a dialog using Toolbar widget.

Android ActionBar in a DialogFragment

Android Toolbar is available through the AppCompat v21 support library. Therefore this widget can be used with Android API 7 and above without any problems. On the other hand DialogFragment class is already available in the support v4 library. Hence an Android ToolBar can be used to display the action bar in a dialog with support from API 7 onwards. To start off please make sure you have AppCompat dependencies in place:

compile 'com.android.support:appcompat-v7:22.1.0'

Next you may need to include Android ToolBar in the dialog layout:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                android:layout_width="match_parent"
                android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/my_toolbar"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="50dp"
        android:layout_marginTop="50dp"/>

</RelativeLayout>

As you can see in the highlighted lines above, I have used the android.support.v7.widget.Toolbar tag to display an action bar in the dialog’s layout. Android Toolbar widget can also be used with the styles defined in your app. As shown above, please use the android:background attribute to specify the color of action bar. Also app:popupTheme and android:theme attributes can be used to display the standard action bar themes as shown. Further lets define the DialogFragment class.

package com.truiton.toolbardialog;

import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

public class ActionBarDialog extends DialogFragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        Bundle args = getArguments();
        String title = args.getString("title");
        View v = inflater.inflate(R.layout.action_bar_dialog, container, false);
        TextView tv = (TextView) v.findViewById(R.id.text);
        tv.setText("This is an instance of ActionBarDialog");
        Toolbar toolbar = (Toolbar) v.findViewById(R.id.my_toolbar);
        toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                // Handle the menu item
                return true;
            }
        });
        toolbar.inflateMenu(R.menu.menu_main);
        toolbar.setTitle(title);
        return v;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        // request a window without the title
        dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
        return dialog;
    }
}

As you can see in the above class, in onCreateDialog method I have applied, no title bar feature. This basically removes the header of DialogFragment. Now we can add our own header, a Toolbar which would act just like an Android ActionBar in the DialogFragment. I would also like to highlight that you can also receive arguments in this dialog from the calling activity by using getArguments() method, as shown above.

Android ActionBar Dialog

Using Android Toolbar instead of ActionBar

As I mentioned, the new Android Toolbar can also be used as a normal action bar in your fragment or activity. But to avoid conflict, first you may need to disable the standard action bar, by using a Theme.AppCompat.NoActionBar theme. Else you would see two action bars. In this example I have specified this theme in the styles.xml as only one activity was there. If you need to use Android ToolBar as an action bar for a specific activity, please use this theme only for that activity. Now lets have a look at styles.xml:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <!--   your app branding color for the app bar -->
        <item name="colorPrimary">#3F51B5</item>
        <!--   darker variant for the status bar and contextual app bars -->
        <item name="colorPrimaryDark">#303F9F</item>
        <!--   theme UI controls like checkboxes and text fields -->
        <item name="colorAccent">#FF4081</item>
    </style>

</resources>

Now that our activity will not be having an action bar, we need to define a Toolbar in the layout as shown:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:app="http://schemas.android.com/apk/res-auto"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                tools:context=".MainActivity">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:background="?attr/colorPrimary"
        android:elevation="8dp"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>

    <ImageView
        android:id="@+id/logo"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:src="@mipmap/truiton_short_no_back"/>

    <Button
        android:id="@+id/dialogButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Launch Dialog with Action Bar"/>

</RelativeLayout>

Now lets have a look at the main activity:

package com.truiton.toolbardialog;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;


public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        Button dialogButton = (Button) findViewById(R.id
                .dialogButton);
        dialogButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Bundle args = new Bundle();
                args.putString("title", "Dialog with Action Bar");
                ActionBarDialog actionbarDialog = new ActionBarDialog();
                actionbarDialog.setArguments(args);
                actionbarDialog.show(getSupportFragmentManager(),
                        "action_bar_frag");
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

As you can see in the above class, that I have used setSupportActionBar(toolbar) method to set the toolbar as default ActionBar. By doing this no extra code needs to be written for using the standard onCreateOptionsMenu and onOptionsItemSelected callback methods. Also please note: in onClick method, I am sending the arguments to ActionBarDialog class, where they are supposed to be used accordingly in the DialogFragment.

Android Toolbar Example

Conclusion

To conclude I would say Android Toolbar widget is a great addition in the AppCompat class. This not only helps in showing an Android action bar in a dialog, but also helps us in many other ways. For example, when multiple action bars are required on a screen, or an action bar of variable width is required. Also Android Toolbar can be used in any layout, to display a fully functional ActionBar/Toolbar. Hope this helps. Connect with us on Facebook, Google+ and Twitter for more updates.

2 thoughts on “Android Action Bar In A Dialog Using ToolBar”

Leave a Reply

Your email address will not be published. Required fields are marked *