Search code examples
androidandroid-actionbarnavigation-drawertoolbar

Android Toolbar for API 19? (for API 21 works ok)


I used How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar? answer of Suyash (I also added a toolbar, maybe incorrectly) to put Navigation Drawer over the "action bar".

For API level 21 instead of "action bar" I used toolbar, and it works fine.

But for API 19 this is not working:

    if(Build.VERSION.SDK_INT > 19) {
      final Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
        setSupportActionBar(toolbar);
    }

Do you have idea how I can put NavigationDrawer over "actionbar" (or toolbar) for API level 19?


Solution

  • If you use Toolbar then you should be able to view the exact same Toolbar in any API.

    For doing that you should have a XML in res/layout:

    <android.support.v7.widget.Toolbar
        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"/>
    

    And in your main layout you should include it:

    <include
        android:id="@+id/app_bar"
        layout="@layout/app_bar" />
    

    Also you should set your style as No Action Bar on your styles.xml

    <style name="AppTheme.Base" parent="Theme.AppCompat.NoActionBar">
        <item name="colorPrimary">@color/primary</item>
        <item name="colorPrimaryDark">@color/primaryDark</item>
        <item name="colorAccent">@color/accent</item>
    </style>
    

    But for API 21 you should have another styles.xml:

    <style name="AppTheme" parent="AppTheme.Base">
        <item name="android:colorPrimary">@color/primary</item>
        <item name="android:colorPrimaryDark">@color/primaryDark</item>
        <item name="android:colorAccent">@color/accent</item>
    </style>
    

    And finally in your Main Activity

    toolbar = (Toolbar) findViewById(R.id.app_bar);
    setSupportActionBar(toolbar);
    

    And finally to any thing you want to do to the toolbar, obtain it and treat it like the old Action Bar:

    getSupportActionBar().setHomeAsUpEnabled(true);