Xamarin - 取代操作栏(Android 7.1 - API 25)

时间:2017-12-24 08:17:02

标签: android xamarin xamarin.android android-actionbar android-toolbar

我尝试通过替换文档中详细说明的默认操作栏来创建工具栏:Part 1 - Replacing the Action Bar,但该应用程序未运行并在SetActionBar(toolbar);处抛出错误。以下是错误消息:

Java.Lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_ACTION_BAR and set android:windowActionBar to false in your theme to use a Toolbar instead.

以下是完整错误:

Unhandled Exception:
Java.Lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_ACTION_BAR and set android:windowActionBar to false in your theme to use a Toolbar instead. 

以下是我所有代码的git repo: Github CustomAndroidToolBar

我正在使用visual studio enterpise 2017,版本15.5

我哪里错了?

1 个答案:

答案 0 :(得分:1)

  

Xamarin - 替换操作栏(Android 7.1 - API 25)

您的项目中存在一些错误。

首先,请阅读此official sample,您使用的是错误的项目。您应该使用

<item name="android:windowNoTitle">. 

而不是

style.xml

像这样修改你的<!-- Base theme applied no matter what API --> <style name="MyTheme" parent="Theme.AppCompat.Light.DarkActionBar"> <item name="windowNoTitle">true</item> <!--We will be using the toolbar so no need to show ActionBar--> <item name="windowActionBar">false</item> <!-- Set theme colors from http://www.google.com/design/spec/style/color.html#color-color-palette--> <!-- colorPrimary is used for the default action bar background --> <item name="colorPrimary">#2196F3</item> <!-- colorPrimaryDark is used for the status bar --> <item name="colorPrimaryDark">#1976D2</item> <!-- colorAccent is used as the default value for colorControlActivated which is used to tint widgets --> <item name="colorAccent">#FF4081</item> </style>

Xamarin.Android.Support.v7.AppCompat

其次,安装AppCompatActivity nuget包

enter image description here

然后为Activityuse a Theme.AppCompat theme (or descendant) with this activity扩展MainActivity而不是MainActivity

请注意虽然您已在项目中编写了自定义主题,但您并未将其用于MainActivity 。您可以阅读文档:Theming an Activity,为您添加主题[Activity(Label = "App3", MainLauncher = true, Theme = "@style/MyTheme")] public class MainActivity : AppCompatActivity { ... }

Android.Widget.Toolbar

第三,在您使用Android.Support.V7.Widget.Toolbar的项目中,请将其更改为MainActivity

var toolbar = FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar); if (toolbar != null) { SetSupportActionBar(toolbar); SupportActionBar.Title = "Hello from Appcompat Toolbar"; }

toolbar.xml

<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" ...

Task::withCount('visits')->latest('visits_count')->get()

然后它在我这边工作得很好。