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

Xamarin - Replacing the Action Bar (Android 7.1 - API 25)

我已尝试完全按照文档中的详细说明通过替换默认操作栏来创建工具栏: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 仓库: Github CustomAndroidToolBar

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

我哪里错了?

Xamarin - Replacing the Action Bar (Android 7.1 - API 25)

你的项目有一些错误。

首先,请阅读这篇文章official sample,你用错了。你应该使用

<item name="windowNoTitle"> 

而不是

<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 nuget包 :

然后为您 MainActivityuse a Theme.AppCompat theme (or descendant) with this activity 扩展 AppCompatActivity 而不是 Activity

请注意,尽管您在项目中编写了自定义主题,但并未将其用于 MainActivity。您可以阅读文档:Theming an Activity,为您添加主题MainActivity

[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"
...

那我这边就没问题了