A toolbar in place of an actionbar with a menu, the end result.
- February 7, 2016
Add references to Xamarin.Android.Support.v7.AppCompat (this will also include Xamarin.Android.Support.v4)
Open Main.axml adding the following toolbar element
<?xml version="1.0" encoding="utf-8"?> <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_height="wrap_content" android:minHeight="?attr/actionBarSize" android:background="?attr/colorPrimary" android:layout_width="match_parent" />
Opening in the designer we have
Updating MainActivity.cs
using System; using Android.App; using Android.Content; using Android.Runtime; using Android.Views; using Android.Widget; using Android.OS; using SupportToolbar = Android.Support.V7.Widget.Toolbar; using Android.Support.V7.App; using Android.Support.V4.Widget; using System.Collections.Generic; namespace AppDave { [Activity(Label = "AppDave", MainLauncher = true, Icon = "@drawable/icon", Theme="@style/MyTheme")] public class MainActivity : ActionBarActivity { private SupportToolbar _toolbar; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); _toolbar = FindViewById<SupportToolbar>(Resource.Id.toolbar); //sets the actionbar to our toolbar SetSupportActionBar(_toolbar); //we can now call our toolbar via SupportActionBar SupportActionBar.Title = "MyToolbar"; } public override bool OnCreateOptionsMenu(IMenu menu) { MenuInflater.Inflate(Resource.Menu.action_menu, menu); return base.OnCreateOptionsMenu(menu); } } }
Notes:
<?xml version="1.0" encoding="utf-8" ?> <resources> <style name="MyTheme" parent="Theme.AppCompat.Light.NoActionBar"> <item name="colorPrimary">#2196F3</item> </style> </resources>
This is the end result, a toolbar in place of an actionbar with a menu<?xml version="1.0" encoding="UTF-8" ?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"><item android:id="@+id/action_help"
android:icon="@drawable/ic_action_help"
android:title="Help"/>
<item android:id="@+id/action_refresh"
android:icon="@drawable/ic_action_refresh"
android:title="Refresh"/>
</menu>
Note: in the above action menu we did not override the app : showAsAction element. If I specify showAsAction in the following manner you can see the differences. When specifying as never the icon is visible to the left of the …
<?xml version="1.0" encoding="UTF-8" ?> <menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/action_help" android:icon="@drawable/ic_action_help" android:title="Help" app:showAsAction="always" /> <item android:id="@+id/action_refresh" android:icon="@drawable/ic_action_refresh" android:title="Refresh" app:showAsAction="never" /> </menu>