Xamarin forms android support v7 widget toolbar

ÇøŋfuzëÐ SøurcëÇødë

This is The ÇøŋfuzëÐ SøurcëÇødë, the Software Engineer. That hyper-active, over enthusiastic, radical developer you may have heard about! This is just a simple attempt to put the source code confusion of my life into words! (^_^)

Let’s Solve, Error inflating class android.support. v7.widget.Toolbar …

So the other day I created a new Xamarin Forms solution in Visual Studio for one of my sample apps, and tried to build and run it.

Something to keep a note here my

  • VS – Xamarin Version – 4.2.2.1
  • VS – Xamarin Android Version – 7.0.2.42
  • Xamarin Forms Version – 2.3.3.180

Build and Run, worked perfectly on iOS.

but on Android?

Then I tried running the Android app, and suddenly at runtime, KABOOM!

Android.Views.InflateException: Binary XML file line #1: Error inflating class android.support.v7.widget.Toolbar…

Without even any build errors, a fresh out of the box project in Visual Studio!

It seemed like some Android dlls were missing in the runtime, something to do with Toolbar. 😮

This didn’t make any sense because I haven’t done any modifications to the project or even written any single line of code in the project, this was just a fresh out of the box Xamarin Forms solution.

So as usual I tried Clean & Rebuild, Restart VS, Restart the PC and so on many other random stuff. But still couldn’t figure out.

A WEIRD SOLUTION!

So as of a final destination I tried downgrading the Xamarin Forms version in the solution, and BOOM! IT WORKED!

So I thought may be this was a bug in the Xamarin Forms version I was using, but just to clarify it I upgraded the Xamarin Forms version back to the original version.

and BOOM! IT WORKED! 😀

Right Click on the Solution -> Manage Nugest Packages -> Select Xamarin.Forms package -> Tick on all the Projects in your Solution -> go to the Version selector -> select a lower Xamarin.Forms version and click Install -> restart VS -> Clean & Rebuild

Then do the same process but when you’re selecting the Xamarin.Forms version, make sure to select the one you had originally at first place when you created your solution! 😉

Probably…

Although this doesn’t really make any sense why it would throw such a runtime error, fresh out of the box, and then magically fixes after downgrading and upgrading back the Xamarin Forms version in the solution, but I’m guessing its something to do with the Xamarin Extension for Visual Studio, which might be messing up with adding some Android dependencies to the solution.

Anyways, I just posted this in any case if you ever came across such a situation yourself! 😀

Источник

Toolbar Compatibility

Overview

This section explains how to use Toolbar on versions of Android earlier than Android 5.0 Lollipop. If your app does not support versions of Android earlier than Android 5.0, you can skip this section.

Because Toolbar is part of the Android v7 support library, it can be used on devices running Android 2.1 (API level 7) and higher. However, the Android Support Library v7 AppCompat NuGet must be installed and the code modified so that it uses the Toolbar implementation provided in this library. This section explains how to install this NuGet and modify the ToolbarFun app from Adding a Second Toolbar so that it runs on versions of Android earlier than Lollipop 5.0.

Читайте также:  Android режим рабочего стола

To modify an app to use the AppCompat version of Toolbar:

Set the Minimum and Target Android versions for the app.

Install the AppCompat NuGet Package.

Use an AppCompat theme instead of a built-in Android theme.

Modify MainActivity so that it subclasses AppCompatActivity rather than Activity .

Each of these steps is explained in detail in the following sections.

Set the Minimum and Target Android Version

The app’s Target Framework must be set to API Level 21 or greater or the app will not deploy properly. If an error such as No resource identifier found for attribute ’tileModeX’ in package ‘android’ is seen while deploying the app, this is because the Target Framework is not set to Android 5.0 (API Level 21 — Lollipop) or greater.

Set the Target Framework level to API Level 21 or greater and set the Android API level project settings to the minimum Android Version that the app is to support. For more information about setting Android API levels, see Understanding Android API Levels. In the ToolbarFun example, the Minimum Android Version is set to KitKat (API Level 4.4).

Install the AppCompat NuGet Package

Next, add the Android Support Library v7 AppCompat package to the project. In Visual Studio, right-click References and select Manage NuGet Packages. . Click Browse and search for Android Support Library v7 AppCompat. Select Xamarin.Android.Support.v7.AppCompat and click Install:

When this NuGet is installed, several other NuGet packages are also installed if not already present (such as Xamarin.Android.Support.Animated.Vector.Drawable, Xamarin.Android.Support.v4, and Xamarin.Android.Support.Vector.Drawable). For more information about installing NuGet packages, see Walkthrough: Including a NuGet in your project.

Use an AppCompat Theme and Toolbar

The AppCompat library comes with several Theme.AppCompat themes that can be used on any version of Android supported by the AppCompat library. The ToolbarFun example app theme is derived from Theme.Material.Light.DarkActionBar , which is not available on Android versions earlier than Lollipop. Therefore, ToolbarFun must be adapted to use the AppCompat counterpart for this theme, Theme.AppCompat.Light.DarkActionBar . Also, because Toolbar is not available on versions of Android earlier than Lollipop, we must use the AppCompat version of Toolbar . Therefore, layouts must use android.support.v7.widget.Toolbar instead of Toolbar .

Update Layouts

Edit Resources/layout/Main.axml and replace the Toolbar element with the following XML:

Edit Resources/layout/toolbar.xml and replace its contents with the following XML:

Note that the ?attr values are no longer prefixed with android: (recall that the ? notation references a resource in the current theme). If ?android:attr were still used here, Android would reference the attribute value from the currently running platform rather than from the AppCompat library. Because this example uses the actionBarSize defined by the AppCompat library, the android: prefix is dropped. Similarly, @android:style is changed to @style so that the android:theme attribute is set to a theme in the AppCompat library – the ThemeOverlay.AppCompat.Dark.ActionBar theme is used here rather than ThemeOverlay.Material.Dark.ActionBar .

Update the Style

Edit Resources/values/styles.xml and replace its contents with the following XML:

The item names and parent theme in this example are no longer prefixed with android: because we are using the AppCompat library. Also, the parent theme is changed to the AppCompat version of Light.DarkActionBar .

Update Menus

To support earlier versions of Android, the AppCompat library uses custom attributes that mirror the attributes of the android: namespace. However, some attributes (such as the showAsAction attribute used in the tag) do not exist in the Android framework on older devices – showAsAction was introduced in Android API 11 but is not available in Android API 7. For this reason, a custom namespace must be used to prefix all of the attributes defined by the support library. In the menu resource files, a namespace called local is defined for prefixing the showAsAction attribute.

Читайте также:  Какую звонилку выбрать для андроид

Edit Resources/menu/top_menus.xml and replace its contents with the following XML:

The local namespace is added with this line:

The showAsAction attribute is prefaced with this local: namespace rather than android:

Similarly, edit Resources/menu/edit_menus.xml and replace its contents with the following XML:

How does this namespace switch provide support for the showAsAction attribute on Android versions prior to API Level 11? The custom attribute showAsAction and all of its possible values are included in the app when the AppCompat NuGet is installed.

Subclass AppCompatActivity

The final step in the conversion is to modify MainActivity so that it is a subclass of AppCompatActivity . Edit MainActivity.cs and add the following using statements:

This declares Toolbar to be the AppCompat version of Toolbar . Next, change the class definition of MainActivity :

To set the action bar to the AppCompat version of Toolbar , substitute the call to SetActionBar with SetSupportActionBar . In this example, the title is also changed to indicate that the AppCompat version of Toolbar is being used:

Finally, change the Minimum Android level to the pre-Lollipop value that is to be supported (for example, API 19).

Build the app and run it on a pre-Lollipop device or Android emulator. The following screenshot shows the AppCompat version of ToolbarFun on a Nexus 4 running KitKat (API 19):

When the AppCompat library is used, themes do not have to be switched based on the Android version – the AppCompat library makes it possible to provide a consistent user experience across all supported Android versions.

Источник

Совместимость панели инструментов

Обзор

В этом разделе объясняется, как использовать Toolbar в версиях Android более ранние, чем android 5,0 без описания операций. Если приложение не поддерживает версии Android, предшествующие Android 5,0, этот раздел можно пропустить.

Так как Toolbar является частью библиотеки поддержки Android версии 7, ее можно использовать на устройствах под управлением android 2,1 (API уровня 7) и более поздних версий. однако библиотека поддержки Android версии 7 AppCompat NuGet должны быть установлены, а код изменен так, чтобы использовать реализацию, предоставленную в этой библиотеке. в этом разделе объясняется, как установить этот NuGet и изменить приложение тулбарфун , добавив вторую панель инструментов , чтобы она выполнялась в версиях Android раньше, чем с параметром без описания 5,0.

Чтобы изменить приложение для использования версии на панели инструментов AppCompat, выполните следующие действия.

Задайте минимальные и целевые версии Android для приложения.

установите пакет AppCompat NuGet.

Используйте тему AppCompat вместо встроенной темы Android.

Измените MainActivity таким образом, чтобы он подклассы, AppCompatActivity а не Activity .

Каждый из этих шагов подробно описан в следующих разделах.

Установка минимальной и целевой версий Android

Целевая платформа приложения должна быть установлена на уровне API 21 или выше, иначе приложение не будет развернуто должным образом. Если при развертывании приложения обнаружена ошибка, например, идентификатор ресурса не найден для атрибута «тилемодекс» в пакете «Android» , это связано с тем, что для целевой платформы не задано значение Android 5,0 (API уровня 21-интерфейса) или больше.

Задайте для целевого уровня платформы уровень API 21 или выше и задайте для параметров проекта уровня API Android минимальную версию Android, которую будет поддерживать приложение. Дополнительные сведения о настройке уровней API Android см. в разделе Общие сведения об уровнях API Android. В этом ToolbarFun примере для минимальной версии Android задано значение KitKat (API уровня 4,4).

Читайте также:  Плеер neutron для андроида

установка пакета AppCompat NuGet

Затем добавьте в проект пакет AppCompat версии 7 для библиотеки поддержки Android . в Visual Studio щелкните правой кнопкой мыши ссылки и выберите пункт управление NuGet пакетами.. Нажмите кнопку Обзор и найдите библиотеку поддержки Android версии 7 AppCompat. Выберите Xamarin. Android. support. версии 7. AppCompat и нажмите кнопку установить.

при установке этого NuGet также устанавливаются несколько других NuGet пакетов, если они отсутствуют (например, xamarin. Android. Support. анимированные. Vector. draw, xamarin. android . support. v4и xamarin. android. support. Vector. draw). дополнительные сведения об установке пакетов NuGet см. в разделе пошаговое руководство. включение NuGet в проект.

Использование темы и панели инструментов AppCompat

Библиотека AppCompat поставляется с несколькими Theme.AppCompat темами, которые можно использовать в любой версии Android, поддерживаемой библиотекой AppCompat. ToolbarFun Тема примера приложения является производной от Theme.Material.Light.DarkActionBar , которая недоступна в версиях Android, предшествующих интерфейсу без описания операций. Поэтому ToolbarFun необходимо адаптироваться к использованию аналога AppCompat для этой темы Theme.AppCompat.Light.DarkActionBar . Кроме того, поскольку Toolbar недоступно в версиях Android, предшествующих интерфейсу без описания операций, необходимо использовать версию AppCompat Toolbar . Поэтому макеты должны использовать android.support.v7.widget.Toolbar вместо Toolbar .

Обновление макетов

Измените Resources/Layout/Main. axml и замените элемент следующим XML-кодом:

Измените Resources/Layout/toolbar.xml и замените его содержимое следующим XML-кодом:

Обратите внимание, что ?attr значения больше не начинаются с префикса android: (Помните, что ? запись ссылается на ресурс в текущей теме). Если ?android:attr все еще использовались здесь, Android будет ссылаться на значение атрибута из текущей платформы, а не из библиотеки AppCompat. Поскольку в этом примере используется объект, actionBarSize определенный библиотекой AppCompat, android: префикс удаляется. Аналогичным образом @android:style изменяется на, чтобы @style android:theme атрибут был установлен в тему в библиотеке AppCompat — ThemeOverlay.AppCompat.Dark.ActionBar здесь используется тема, а не ThemeOverlay.Material.Dark.ActionBar .

Обновление стиля

Измените Resources/Values/styles.xml и замените его содержимое следующим XML-кодом:

Имена элементов и родительские темы в этом примере больше не являются префиксами, android: так как мы используем библиотеку AppCompat. Кроме того, Родительская тема изменяется на версию AppCompat Light.DarkActionBar .

Обновить меню

Для поддержки более ранних версий Android библиотека AppCompat использует настраиваемые атрибуты, отражающие атрибуты android: пространства имен. Однако некоторые атрибуты (например, атрибут, showAsAction используемый в теге) не существуют в платформе Android на старых устройствах showAsAction . они появились в интерфейсе API Android 11, но недоступны в API Android 7. По этой причине для префикса всех атрибутов, определенных библиотекой поддержки, необходимо использовать пользовательское пространство имен. В файлах ресурсов меню local для префикса атрибута определено пространство имен с именем showAsAction .

Измените ресурсы/меню/top_menus.xml и замените его содержимое следующим XML-кодом:

local Пространство имен добавляется с этой строкой:

showAsAction Этот атрибут предшествует этому local: пространству имен, а не android:

Аналогичным образом измените Resources/Menu/edit_menus.xml и замените его содержимое следующим XML-кодом:

Как этот переключатель пространства имен обеспечивает поддержку showAsAction атрибута в версиях Android до уровня API 11? пользовательский атрибут showAsAction и все возможные значения включаются в приложение при установке AppCompat NuGet.

Подкласс Аппкомпатактивити

Последним шагом в преобразовании является изменение MainActivity , чтобы он был подклассом AppCompatActivity . Измените MainActivity. CS и добавьте следующие инструкции:

Это объявляется как Toolbar версия AppCompat Toolbar . Затем измените определение класса MainActivity :

Чтобы задать панель действий для версии AppCompat Toolbar , замените вызов на SetActionBar SetSupportActionBar . В этом примере заголовок также изменяется, указывая, что используется версия AppCompat Toolbar :

Наконец, измените минимальный уровень Android на значение предварительной версии, которое должно поддерживаться (например, API 19).

Выполните сборку приложения и запустите его на устройстве предварительной версии или эмуляторе Android. На следующем снимке экрана показана версия совместимости тулбарфун для хранилища 4 с KITKAT (API 19):

При использовании библиотеки AppCompat темы не обязательно переключаются на основе версии Android — библиотека AppCompat позволяет обеспечить единообразное взаимодействие с пользователем во всех поддерживаемых версиях Android.

Источник

Оцените статью