![]() |
![]() |
toolbar در زامارین
در ادامه آموزش قبل ، فولدری با نام menu در قسمت resources ایجاد می کنیم و فایل xml ، با نام action_menu.xml را ایجاد میکنیم و داخل این فایل xml، از طریق تگ item میتوانیم آیتم های لازم را مشخص کنیم و برای آنها آیکون و تیتر قرار دهیم.(مشابه با آموزش actionbar در زامارین)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:local="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/menu_share" android:icon="@drawable/ic_action_social_share" local:showAsAction="ifRoom" android:title="Share" /> <item android:id="@+id/menu_settings" local:showAsAction="never" android:title="Settings" /> </menu> |
به main activity می رویم چون از toolbar موجود در کتابخانه support v7 استفاده کرده ایم در ابتدا در همان using ،toolbar آن را تعریف خواهیم کرد.
1 2 3 |
using SupportToolbar = Android.Support.V7.Widget.Toolbar; |
با کد زیر ، toolbar را جایگزین اکشن بار می کنیم.
1 2 3 |
SetSupportActionBar(_toolbar); |
عنوان toolbar را نیز با کد زیر مشخص میکنیم.
1 2 3 |
SupportActionBar.Title = "MyToolbar"; |
و متد OnCreateOptionsMenu را override کنیم.
1 2 3 4 5 6 7 8 9 |
public override bool OnCreateOptionsMenu(IMenu menu) { MenuInflater.Inflate(Resource.Menu.action_menu, menu); return base.OnCreateOptionsMenu(menu); } |
و کل main activity به شکل زیر خواهد بود.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
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 toolbar { [Activity(Label = "Toolbar", MainLauncher = true, Icon = "@drawable/icon", Theme = "@style/MyTheme")] public class MainActivity : AppCompatActivity { private SupportToolbar _toolbar; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); SetContentView(Resource.Layout.Main); _toolbar = FindViewById(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); } } } |