Error inflating class com google android material navigation navigationview

After I updated my project to AndroidX with targetSdkVersion set to 28, my project crashes when installing it from the store for beta testing. The following is the error log I receive: 2019-07-08 0...

After I updated my project to AndroidX with targetSdkVersion set to 28, my project crashes when installing it from the store for beta testing.

The following is the error log I receive:

2019-07-08 08:28:33.026 32011-32011/? E/AndroidRuntime: FATAL EXCEPTION: main Process: hu.itq.oakprotection, PID: 32011
        java.lang.RuntimeException: Unable to start activity ComponentInfo{hu.itq.oakprotection/hu.itq.oakprotection.MainActivity}: android.view.InflateException: Binary XML file line #15: Binary XML file line #15: Error inflating class com.google.android.material.navigation.NavigationView
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3194)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3302)
            at android.app.ActivityThread.-wrap12(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1891)
            at android.os.Handler.dispatchMessage(Handler.java:108)
            at android.os.Looper.loop(Looper.java:166)
            at android.app.ActivityThread.main(ActivityThread.java:7425)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
         Caused by: android.view.InflateException: Binary XML file line #15: Binary XML file line #15: Error inflating class com.google.android.material.navigation.NavigationView
         Caused by: android.view.InflateException: Binary XML file line #15: Error inflating class com.google.android.material.navigation.NavigationView
         Caused by: java.lang.reflect.InvocationTargetException
            at java.lang.reflect.Constructor.newInstance0(Native Method)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
            at android.view.LayoutInflater.createView(LayoutInflater.java:658)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:801)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:874)
            at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:835)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
            at androidx.appcompat.app.AppCompatDelegateImpl.c(Unknown Source:23)
            at androidx.appcompat.app.AppCompatActivity.setContentView(Unknown Source:4)
            at hu.itq.oakprotection.MainActivity.onCreate(Unknown Source:6)
            at android.app.Activity.performCreate(Activity.java:7372)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1218)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3147)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3302)
            at android.app.ActivityThread.-wrap12(Unknown Source:0)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1891)
            at android.os.Handler.dispatchMessage(Handler.java:108)
            at android.os.Looper.loop(Looper.java:166)
            at android.app.ActivityThread.main(ActivityThread.java:7425)
            at java.lang.reflect.Method.invoke(Native Method)
            at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:245)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:921)
         Caused by: java.lang.NoSuchMethodError: No interface method d()I in class Lorg/xmlpull/v1/XmlPullParser; or its super classes (declaration of 'org.xmlpull.v1.XmlPullParser' appears in /system/framework/core-libart.jar)
            at androidx.appcompat.view.SupportMenuInflater.a(Unknown Source:5)
            at androidx.appcompat.view.SupportMenuInflater.inflate(Unknown Source:25)
            at com.google.android.material.navigation.NavigationView.b(Unknown Source:12)
            at com.google.android.material.navigation.NavigationView.<init>(Unknown Source:255)
            at com.google.android.material.navigation.NavigationView.<init>(Unknown Source:2)
            at java.lang.reflect.Constructor.newInstance0(Native Method) 
            at java.lang.reflect.Constructor.newInstance(Constructor.java:334) 

The following are my dependencies in build.gradle file:

android {
    compileSdkVersion 28
    def versionMajor = 1
    def versionMinor = 0
    def versionPatch = 1
    def versionBuild = 4 // ezt kell átírni új verzió kirakásakor

    defaultConfig {
        applicationId "hu.itq.oakprotection"
        minSdkVersion 23
        targetSdkVersion 28
        versionCode versionMajor * 10000 + versionMinor * 1000 + versionPatch * 100 + versionBuild
        versionName "${versionMajor}.${versionMinor}.${versionPatch}"
    }
    buildTypes {
        release {
            minifyEnabled true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        targetCompatibility 1.8
        sourceCompatibility 1.8
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')

    implementation 'androidx.core:core:1.0.2'
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.annotation:annotation:1.1.0'

    implementation 'com.payumoney.sdkui:plug-n-play:1.2.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    implementation 'com.google.android.material:material:1.1.0-alpha07'
    implementation 'androidx.browser:browser:1.0.0'
    implementation 'com.google.android.gms:play-services-base:17.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    //Test error miatt kellett
    implementation 'androidx.annotation:annotation:1.1.0'

    //Aszinkron hálózatokhoz
    implementation 'com.android.volley:volley:1.1.1'

    //Facebook
    implementation 'com.facebook.android:facebook-android-sdk:4.34.0'
    //Osm Droid
    implementation 'org.osmdroid:osmdroid-android:6.1.0'
    implementation 'com.github.MKergall:osmbonuspack:6.4'

    implementation 'com.github.angads25:filepicker:1.1.1'
    //Tile provider igényli
    implementation 'mil.nga.geopackage:geopackage-android:3.0.2'
    implementation 'com.j256.ormlite:ormlite-android:5.1'
    implementation 'mil.nga.geopackage:geopackage-core:3.0.2'
    implementation 'ar.com.hjg:pngj:2.1.0'
    implementation 'mil.nga:tiff:2.0.0'
    implementation('mil.nga.geopackage:geopackage-android:3.0.2') {
        exclude group: 'com.google.android.gms', module: 'play-services'
        exclude group: 'com.google.maps.android', module: 'android-maps-utils'
        exclude group: 'com.android.support', module: 'support-v13'
    }
    //Glide
    implementation 'com.github.bumptech.glide:glide:4.8.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.8.0'
    //Mapsforge rendering and database support, which is LGPL
    implementation 'org.mapsforge:mapsforge-map-android:0.8.0'
    implementation 'org.mapsforge:mapsforge-map:0.8.0'
    implementation 'org.mapsforge:mapsforge-themes:0.8.0'
    // ExoPlayer
    implementation 'com.google.android.exoplayer:exoplayer:2.7.3'
    //Youtube
    implementation 'com.github.HaarigerHarald:android-youtubeExtractor:v1.7.0'}

activity_main.xml:

<androidx.drawerlayout.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start"
    tools:context=".MainActivity">

    <include
        layout="@layout/app_bar_main" />

    <com.google.android.material.navigation.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer"
        app:itemIconTint="@color/colorPrimary"
        app:itemTextColor="@color/colorPrimary"
        android:backgroundTint="@color/colorWhite"/>

</androidx.drawerlayout.widget.DrawerLayout>

Why am I receiving an android.view.InflateException error for NavigationView?

This is probably down to api version. The latest changelog sais it now depends on android ‘Q’ sdk, while I’m using 28 still. I’m gonna keep using 07 for the time being and try this again at the weekend. Don’t really have that great of an internet until then to be downloading preview versions of android studio and the new sdk.


We don’t have to depend on all those things mentioned in the changelog in our project do we? Since, right now the libraries I depend on in my project are these

    implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
    implementation "org.jetbrains.kotlinx:kotlinx-serialization-runtime:0.11.1"
    implementation 'org.jetbrains.anko:anko-commons:0.10.8'
    implementation 'org.jetbrains.anko:anko-sqlite:0.10.8'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-core:1.2.1"
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.2.1"

    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.lifecycle:lifecycle-viewmodel-ktx:2.0.0'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.0.0'
    implementation 'com.google.android.material:material:1.1.0-alpha07'

So the only library mentioned in the changelog I depend on would be androidx.appcompat:appcompat. I tried updating that to the version mentioned in the changelog, but that didn’t help. As I said I’ll keep it like this for the time being.

Содержание

  1. Русские Блоги
  2. MaterialCardView Материальных Компонентов
  3. Material Card
  4. Применение
  5. собственности
  6. Ошибка при запуске приложения на AndroidStudio?
  7. Hands-on with Material Components for Android: Cards
  8. Part 6 of a series covering practical usage of Material Components for Android
  9. Setting up a Material Components theme for Android
  10. Attribute by attribute
  11. Basic usage 🏁
  12. Checking ☑️
  13. Dragging and swipe-to-dismiss ☝️
  14. Theming 🎨
  15. Color
  16. Typography
  17. Shape
  18. More resources 📚
  19. Name already in use
  20. material-components-android / docs / components / Card.md
  21. Users who have contributed to this file

Русские Блоги

MaterialCardView Материальных Компонентов

Material Card

Карта — это элемент управления, который может содержать фотографии, текст и ссылки на одну тему. Они могут отображать контент с элементами разных размеров, например, фотографии с субтитрами переменной длины.

MaterialCardView — это настраиваемый компонент, основанный на CardView в библиотеке поддержки Android. MaterialCardView предоставляет все функции CardView, но добавляет некоторые пользовательские атрибуты, которые более удобны и практичны в использовании.

Примечание. MaterialCardView — это постоянная реализация Google, которая продолжит разработку новых функций и обновлений. Большинство из этих обновлений будут основаны на стиле и будут иметь дополнительные параметры для размещения содержимого (например, разделители, изображения, действия и обработка текста). Обновление также будет включать в себя функцию поведения карты в колоде.

Применение

Чтобы использовать MaterialCardView, вам необходимо представить библиотеку элементов управления:

Таким образом, вы можете использовать больше, чем просто MaterialCardView и другие элементы управления материалом.

Перед его использованием вам необходимо изменить свой AppTheme на Theme.MaterialComponents или его подклассы, в противном случае вы получите ошибку:

Если ваш файл манифеста (AndroidManifest.xml) находится в приложении android:theme=»@style/AppTheme» Затем измените его в style.xml:

После выполнения предыдущих операций, вы можете добавить MaterialCardView в файл макета

непроверенный

выбранное состояние

собственности

Атрибуты XML

характерная черта Связанные атрибуты
Border app:strokeColor app:strokeWidth
Checkable android:checkable
Checked Icon app:checkedIcon app:checkedIconTint
Foreground Color app:cardForegroundColor
Ripple Color app:rippleColor

Конечно, вы также можете использовать некоторые методы в коде Java / Kotlin:

Источник

Ошибка при запуске приложения на AndroidStudio?

Добрый день! При запуске приложения вылетает такая вот ошибка:

Caused by: android.view.InflateException: Binary XML file line #8: Binary XML file line #8: Error inflating class com.google.android.material.navigation.NavigationView
Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class com.google.android.material.navigation.NavigationView
Caused by: java.lang.reflect.InvocationTargetException

и приложение закрывается. Подскажите как исправить.

  • Вопрос задан более двух лет назад
  • 444 просмотра

Простой 1 комментарий

Из описания следует, что нужно исправить ошибку в XML разметке в строке 8.

Я только начинаю, может подскажите подробнее? Чего не хватает?

dependencies <
implementation ‘com.mxn.soul:flowingdrawer-core:2.1.0’
implementation ‘com.nineoldandroids:library:2.4.0’
implementation fileTree(dir: «libs», include: [«*.jar»])
implementation ‘androidx.appcompat:appcompat:1.1.0’
implementation ‘androidx.constraintlayout:constraintlayout:1.1.3’
implementation ‘androidx.coordinatorlayout:coordinatorlayout:1.1.0’
implementation ‘com.google.android.material:material:1.1.0’
testImplementation ‘junit:junit:4.12’
androidTestImplementation ‘androidx.test.ext:junit:1.1.1’
androidTestImplementation ‘androidx.test.espresso:espresso-core:3.2.0’

Как искать ответ самому.
Видим ругается на Error inflating class com.google.android.material.navigation.NavigationView
гуглим com.google.android.material.navigation.navigationview implementation
нагугливается, что это com.shreyaspatil

Удивляемся. Пока гуглили заметили, что в пустом проекте можно попробывать сделать через визард активностей.

Пробуем. И видим.

implementation ‘androidx.navigation:navigation-fragment:2.3.0’
implementation ‘androidx.navigation:navigation-ui:2.3.0’

ок. открываем лайоут .
становимся на com.google.android.material.navigation.NavigationView
нажимаем аккорд Ctrl+B — мой любимый — перейти туда где это было определено.

попадаем в класс
мотаем вверх смотрим
package com.google.android.material.navigation;

подымем взгляд еще выше на заголовок окна и видим
com.google.android.material:material:1.1.0@aar

Мое первое предположение оказалось ложным.

Возвращаемся на лайоут.
Редим предпросмотра. Серыми квадратами рисуется, то что не смогла система правильно распознать.
Забыли подключить или написали неправильно.

Режим текстового просмотра. Что нибудь подчеркивается. Значки предупреждения в виде дерева

Источник

Hands-on with Material Components for Android: Cards

Part 6 of a series covering practical usage of Material Components for Android

This post will be covering the features and API of Card components. To find out how to handle initial setup of Material Components for Android (including the Gradle dependency and creating an app theme), please see my original post:

Setting up a Material Components theme for Android

Attribute by attribute

Cards are sheets of surface material that contain content and actions related to a single subject. This content may include text, images, links and more, and may vary in size. While there are many patterns and variations in terms of content layout, the only required element is the card container.

Basic usage 🏁

A MaterialCardView can be included in your layout like so:

Checking ☑️

A MaterialCardView can be checked to indicate selection. There is no default behavior for enabling/disabling checked state; this can be done in response to long press, for example.

Firstly, checkable behavior needs to be enabled:

We can then toggle checked state (the below example is in response to a long click):

The UI changes include an overlay color and a checked icon:

The checked icon can be changed using the checkedIcon attribute. The various color options will be discussed in the “Theming” section below.

For an advanced checking sample using RecyclerView selection, see the Material Components for Android catalog.

Dragging and swipe-to-dismiss ☝️

MaterialCardView s have built-in support for state changes specific to dragging. As with checking, no default behavior exists to implement the dragging itself. The recommended way of doing this is with ViewDragHelper and the Material Components for Android catalog includes a handy implementation class; DraggableCoordinatorLayout .

Note: It would be useful if DraggableCoordinatorLayout were included in the core Material Components for Android library to allow it to be used without having to copy the class. At the time of writing, the latest release of Material Components for Android is 1.2.0-alpha06 and this is not the case. You can star the feature request for this on the issue tracker.

Firstly, we need to change the parent container to a DraggableCoordinatorLayout :

We can then add a callback and toggle dragged state:

The UI changes include an overlay color and (animated) increased elevation:

For an advanced dragging sample using RecyclerView drag-and-drop, see the Material Components for Android catalog.

Theming 🎨

Cards can be themed in terms of the three Material Theming subsystems: color, typography and shape. When implementing a global card style, extend the Widget.MaterialComponents.CardView style and reference it in your app theme with the materialCardViewStyle attribute.

Color

The color of the card background can be customized with the cardBackgroundColor attribute. This defaults to colorSurface .

As mentioned above, the foreground color of a card is used to indicate both checked and dragged state. As such, this requires a ColorStateList , meaning a for checked/dragged states is required. It is usually transparent but uses color to indicate checking/dragging, defaulting to colorPrimary (checked)/ colorOnSurface (dragged), with different opacities per state.

The tint color of the checked icon can be customized with the checkedIconTint attribute. This defaults to colorPrimary .

The color of an optional card stroke can be customized with the strokeColor attribute. This is disabled by default.

Lastly, the color of the card touch ripple can be customized with the rippleColor attribute. It too accepts a ColorStateList and defaults to colorOnSurface (unchecked)/ colorPrimary (checked), with different opacities per state.

Typography

There is no primary text as part of card components. Text included in the contents of a card will be styled according to the class/component used as well as the fontFamily app theme attribute.

Shape

The shape of a card background can be customized with the shapeAppearance attribute. This defaults to shapeAppearanceMediumComponent .

The elevation of a card can be customized with the cardElevation attribute. This defaults to 1dp.

Interestingly, the corner size of a card’s current shape appearance can be interpolated between 0.0 and 1.0. This can be useful in animations and transitions. Use MaterialCardView#setProgress and MaterialCardView#getProgress for this.

While not strictly shape theming, it is worth mentioning that the width of an optional card stroke can be adjusted with the strokeWidth attribute. This defaults to 0dp (and will not be rendered if no strokeColor is set, regardless of width).

More resources 📚

  • The source code for the Playground app used in this article can be found on GitHub.
  • Cards Design Documentation
  • Cards API Documentation

I hope this post has provided some insight into Cards and how they can be used in your Android app(s). If you have any questions, thoughts or suggestions then I’d love to hear from you!

Источник

Name already in use

material-components-android / docs / components / Card.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink

5 contributors

Users who have contributed to this file

Copy raw contents

Copy raw contents

Cards contain content and actions about a single subject.

Contents

Before you can use a Material card, you need to add a dependency to the Material Components for Android library. For more information, go to the Getting started page.

Cards support checking and dragging, but those behaviors are not implemented by default.

Making cards accessible

The contents within a card should follow their own accessibility guidelines, such as images having content descriptions set on them.

If you have a draggable card, you should set an AccessibilityDelegate on it, so that the behavior can be accessible via screen readers such as TalkBack. See the draggable card section below for more info.

Making a card checkable

When a card is checked, it will show a checked icon and change its foreground color. There is no default behavior for enabling/disabling the checked state. An example of how to do it in response to a long click is shown below.

Making a card draggable

Cards have an app:state_dragged with foreground and elevation changes to convey motion. We recommend using ViewDragHelper to set the dragged state:

Alternatively, the Material Catalog has an implementation example that you can copy, which uses a custom class called DraggableCoordinatorLayout . It is used as the parent container in the layout:

Finally, make sure the behavior is accessible by setting an AccessibilityDelegate on the card. The code below demonstrates how to allow the user to move the card to two different positions on the screen.

Note: Cards also support a swipe-to-dismiss behavior through the use of ‘SwipeDismissBehavior’. You can see an example here.

On mobile, an outlined or a filled card’s default elevation is 0dp , with a raised dragged elevation of 8dp . The Material Android library also provides an elevated card style, which has an elevation of 1dp , with a raised dragged elevation of 2dp .

API and source code:

Note: You don’t need to specify a style tag as long as you are using a Material Components Theme. If not, set the style to Widget.Material3.CardView.Outlined , Widget.Material3.CardView.Filled or Widget.Material3.CardView.Elevated .

The following example shows an outlined card.

The following example shows an filled card.

The following example shows an elevated card.

Anatomy and key properties

A card has a container and an optional thumbnail, header text, secondary text, media, supporting text, buttons and icons.

  1. Container
  2. Headline
  3. Subhead
  4. Supporting text
  5. Image
  6. Buttons

Note: All the optional elements of a card’s content (with the exception of the checked icon) are implemented through the use of other views/components, as shown in the card examples section.

Element Attribute Related method(s) Default value
Color app:cardBackgroundColor setCardBackgroundColor
getCardBackgroundColor
?attr/colorSurface or ?attr/colorSurfaceVariant (filled style)
Foreground color app:cardForegroundColor setCardForegroundColor
getCardForegroundColor
@android:color/transparent (see all states)
Stroke color app:strokeColor setStrokeColor
getStrokeColor
getStrokeColorStateList
?attr/colorOutline (unchecked)
?attr/colorSecondary (checked)
Stroke width app:strokeWidth setStrokeWidth
getStrokeWidth
1dp (outlined style)
0dp (elevated or filled style)
Shape app:shapeAppearance setShapeAppearanceModel
getShapeAppearanceModel
?attr/shapeAppearanceMediumComponent
Elevation app:cardElevation setCardElevation
setCardMaxElevation
0dp (outlined or filled style)
1dp (elevated style)
Ripple color app:rippleColor setRippleColor
setRippleColorResource
getRippleColor
?attr/colorOnSurfaceVariant at 20% opacity (see all states)

Note: We recommend that cards on mobile have 8dp margins. android:layout_margin will NOT work in default styles (for example materialCardViewStyle ) so either set this attr directly on a MaterialCardView in the layout or add it to a style that is applied in the layout with style=»@style/. .

Note: Without an app:strokeColor , the card will not render a stroked border, regardless of the app:strokeWidth value.

Checked icon attributes

Element Attribute Related method(s) Default value
Icon checkedIcon setCheckedIcon
setCheckedIconResource
getCheckedIcon
@drawable/ic_mtrl_checked_circle.xml
Color checkedIconTint setCheckedIconTint
getCheckedIconTint
?attr/colorOutline (unchecked)
?attr/colorSecondary (checked)
Checkable android:checkable setCheckable
isCheckable
false
Size checkedIconSize setCheckedIconSize
setCheckedIconSizeResource
getCheckedIconSize
24dp
Margin checkedIconMargin setCheckedIconMargin
setCheckedIconMarginResource
getCheckedIconMargin
8dp
Gravity checkedIconGravity setCheckedIconGravity
getCheckedIconGravity
TOP_END

Cards can have the following states:

State Description Related method(s)
Default Card is not checked and not dragged N/A
Checked ( android:state_checked ) true if a card is checked setChecked
setOnCheckedChangeListener
isChecked
Dragged ( app:state_dragged ) true when a card is being dragged setDragged
isDragged
Element Style
Default style Widget.Material3.CardView.Outlined

Default style theme attribute: ?attr/materialCardViewStyle

Additional style theme attributes: ?attr/materialCardViewOutlinedStyle , ?attr/materialCardViewFilledStyle , ?attr/materialCardViewElevatedStyle

See the full list of styles and attributes.

A card supports Material Theming and can be customized in terms of color, typography and shape.

Card theming example

API and source code

The following example shows a card with Material Theming.

Implementing card theming

Use theme attributes and a style in res/values/styles.xml to apply the theme to all cards. This will affect other components:

Use a default style theme attribute, styles and a theme overlay. This applies a theme to all cards but does not affect other components:

Use the style in the layout. This affects only this specific card:

In order to optimize shape theming, some (optional) adjustments need to be made to the card layout to incorporate ShapeableImageView.

Note: In order to apply a theme to card contents (text, buttons, etc.), the relevant styles/attributes for these components need to be included. For more information, see the article on buttons.

Источник

Султан

4 / 4 / 0

Регистрация: 11.03.2012

Сообщений: 120

1

22.11.2019, 23:03. Показов 4638. Ответов 4

Метки нет (Все метки)


Здравствуйте. Возникла проблема при запуске приложения. Если удалить все поле NavigationView, то приложение запускается.

Вот разметка в которой возникает ошибка.

XML
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
<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
 
        <include
            layout="@layout/toolbar_main"
            android:id="@+id/toolbar"/>
 
        <FrameLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/content_frame"/>
    </LinearLayout>
 
    <com.google.android.material.navigation.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/nav_view"
        android:layout_gravity="start"
        app:headerLayout="@layout/nav_header"
        app:menu="@menu/menu_nav"/>
 
</androidx.drawerlayout.widget.DrawerLayout>

Код активности

Java
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
package com.example.catchat;
 
import androidx.appcompat.app.AppCompatActivity;
 
import android.os.Bundle;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentTransaction;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
 
        Fragment fragment = new InboxFragment();
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.add(R.id.content_frame, fragment);
        ft.commit();
    }
}

подключенные библиотеки

Java
1
2
3
4
5
6
7
8
9
10
11
dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    implementation 'com.google.android.material:material:1.0.0'
    implementation 'com.android.support:design:28.0.0'
}

Собственно сам лог

Кликните здесь для просмотра всего текста

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.catchat, PID: 8328
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.catchat/com.example.catchat.MainActivity}: android.view.InflateException: Binary XML file line #24 in com.example.catchat:layout/activity_main: Binary XML file line #24 in com.example.catchat:layout/activity_main: Error inflating class com.google.android.material.navigation.NavigationV iew
at android.app.ActivityThread.performLaunchActivity(A ctivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(Ac tivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.e xecute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor. executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor. execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(Activit yThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:10 7)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.jav a:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsC aller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit .java:930)
Caused by: android.view.InflateException: Binary XML file line #24 in com.example.catchat:layout/activity_main: Binary XML file line #24 in com.example.catchat:layout/activity_main: Error inflating class com.google.android.material.navigation.NavigationV iew
Caused by: android.view.InflateException: Binary XML file line #24 in com.example.catchat:layout/activity_main: Error inflating class com.google.android.material.navigation.NavigationV iew
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Construc tor.java:343)
at android.view.LayoutInflater.createView(LayoutInfla ter.java:854)
at android.view.LayoutInflater.createViewFromTag(Layo utInflater.java:1006)
at android.view.LayoutInflater.createViewFromTag(Layo utInflater.java:961)
at android.view.LayoutInflater.rInflate(LayoutInflate r.java:1123)
at android.view.LayoutInflater.rInflateChildren(Layou tInflater.java:1084)
at android.view.LayoutInflater.inflate(LayoutInflater .java:682)
at android.view.LayoutInflater.inflate(LayoutInflater .java:534)
at android.view.LayoutInflater.inflate(LayoutInflater .java:481)
at androidx.appcompat.app.AppCompatDelegateImpl.setCo ntentView(AppCompatDelegateImpl.java:555)
at androidx.appcompat.app.AppCompatActivity.setConten tView(AppCompatActivity.java:161)
at com.example.catchat.MainActivity.onCreate(MainActi vity.java:15)
at android.app.Activity.performCreate(Activity.java:7 802)
at android.app.Activity.performCreate(Activity.java:7 791)
at android.app.Instrumentation.callActivityOnCreate(I nstrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(A ctivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(Ac tivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.e xecute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor. executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor. execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(Activit yThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:10 7)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.jav a:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsC aller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit .java:930)
E/AndroidRuntime: Caused by: android.view.InflateException: Binary XML file line #21 in com.example.catchat:layout/nav_header: Binary XML file line #21 in com.example.catchat:layout/nav_header: Error inflating class TextView
Caused by: android.view.InflateException: Binary XML file line #21 in com.example.catchat:layout/nav_header: Error inflating class TextView
Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 4: TypedValue{t=0x2/d=0x1010099 a=1}
at android.content.res.TypedArray.getColor(TypedArray .java:527)
at android.widget.TextView.readTextAppearance(TextVie w.java:3958)
at android.widget.TextView.<init>(TextView.java:1027)
at android.widget.TextView.<init>(TextView.java:968)
at androidx.appcompat.widget.AppCompatTextView.<init> (AppCompatTextView.java:99)
at androidx.appcompat.widget.AppCompatTextView.<init> (AppCompatTextView.java:95)
at androidx.appcompat.app.AppCompatViewInflater.creat eTextView(AppCompatViewInflater.java:182)
at androidx.appcompat.app.AppCompatViewInflater.creat eView(AppCompatViewInflater.java:103)
at androidx.appcompat.app.AppCompatDelegateImpl.creat eView(AppCompatDelegateImpl.java:1407)
at androidx.appcompat.app.AppCompatDelegateImpl.onCre ateView(AppCompatDelegateImpl.java:1457)
at android.view.LayoutInflater.tryCreateView(LayoutIn flater.java:1061)
at android.view.LayoutInflater.createViewFromTag(Layo utInflater.java:997)
at android.view.LayoutInflater.createViewFromTag(Layo utInflater.java:961)
at android.view.LayoutInflater.rInflate(LayoutInflate r.java:1123)
at android.view.LayoutInflater.rInflateChildren(Layou tInflater.java:1084)
at android.view.LayoutInflater.rInflate(LayoutInflate r.java:1126)
at android.view.LayoutInflater.rInflateChildren(Layou tInflater.java:1084)
at android.view.LayoutInflater.inflate(LayoutInflater .java:682)
at android.view.LayoutInflater.inflate(LayoutInflater .java:534)
at com.google.android.material.internal.NavigationMen uPresenter.inflateHeaderView(NavigationMenuPresent er.java:207)
at com.google.android.material.navigation.NavigationV iew.inflateHeaderView(NavigationView.java:281)
at com.google.android.material.navigation.NavigationV iew.<init>(NavigationView.java:193)
at com.google.android.material.navigation.NavigationV iew.<init>(NavigationView.java:104)
at java.lang.reflect.Constructor.newInstance0(Native Method)
at java.lang.reflect.Constructor.newInstance(Construc tor.java:343)
at android.view.LayoutInflater.createView(LayoutInfla ter.java:854)
at android.view.LayoutInflater.createViewFromTag(Layo utInflater.java:1006)
at android.view.LayoutInflater.createViewFromTag(Layo utInflater.java:961)
at android.view.LayoutInflater.rInflate(LayoutInflate r.java:1123)
at android.view.LayoutInflater.rInflateChildren(Layou tInflater.java:1084)
at android.view.LayoutInflater.inflate(LayoutInflater .java:682)
at android.view.LayoutInflater.inflate(LayoutInflater .java:534)
at android.view.LayoutInflater.inflate(LayoutInflater .java:481)
at androidx.appcompat.app.AppCompatDelegateImpl.setCo ntentView(AppCompatDelegateImpl.java:555)
at androidx.appcompat.app.AppCompatActivity.setConten tView(AppCompatActivity.java:161)
at com.example.catchat.MainActivity.onCreate(MainActi vity.java:15)
at android.app.Activity.performCreate(Activity.java:7 802)
at android.app.Activity.performCreate(Activity.java:7 791)
at android.app.Instrumentation.callActivityOnCreate(I nstrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(A ctivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(Ac tivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.e xecute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor. executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor. execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(Activit yThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:10 7)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.jav a:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsC aller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit .java:930)

Помогите разобраться с проблемой

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Gukamanav

14 / 13 / 4

Регистрация: 11.08.2016

Сообщений: 87

22.11.2019, 23:58

2

Java
1
E/AndroidRuntime: Caused by: android.view.InflateException: Binary XML file line #21 in com.example.catchat:layout/nav_header: Binary XML file line #21 in com.example.catchat:layout/nav_header: Error inflating class TextView

Проверьте корректность лэйаут фвйлов которые использует ваш navigationview и обозначьте ваш navigationview в mainactivity=)



1



Султан

4 / 4 / 0

Регистрация: 11.03.2012

Сообщений: 120

23.11.2019, 08:04

 [ТС]

3

Gukamanav, navigationview использует nav_header и menu_nav

XML
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
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="180dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">
 
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:scaleType="centerCrop"
        android:src="@drawable/kitten_small"/>
 
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="bottom|start"
        android:layout_margin="16dp">
 
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/app_name"
            android:theme="@style/TextAppearance.AppCompat.Body1" />
 
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/user_name" />
 
    </LinearLayout>
</FrameLayout>
XML
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
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
 
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_inbox"
            android:icon="@android:drawable/sym_action_email"
            android:title="@string/nav_inbox"
            android:checked="true" />
        <item
            android:id="@+id/nav_drafts"
            android:icon="@android:drawable/ic_menu_edit"
            android:title="@string/nav_drafts" />
        <item
            android:id="@+id/nav_sent"
            android:icon="@android:drawable/ic_menu_send"
            android:title="@string/nav_sent" />
        <item
            android:id="@+id/nav_trash"
            android:icon="@android:drawable/ic_menu_delete"
            android:title="@string/nav_trash" />
    </group>
 
    <item android:title="@string/nav_support">
        <menu>
            <item
                android:id="@+id/nav_help"
                android:icon="@android:drawable/ic_menu_help"
                android:title="@string/nav_help" />
            <item
                android:id="@+id/nav_feedback"
                android:icon="@android:drawable/sym_action_email"
                android:title="@string/nav_feedback" />
        </menu>
    </item>
</menu>

Я не вижу в них ошибки пока что.



0



14 / 13 / 4

Регистрация: 11.08.2016

Сообщений: 87

23.11.2019, 14:33

4

У вас в мэйн активити не описан ваш navigation view. Ознакомьтесь: https://habr.com/ru/post/449776/



0



4 / 4 / 0

Регистрация: 11.03.2012

Сообщений: 120

24.11.2019, 14:22

 [ТС]

5

Gukamanav, нет, что бы все работало не нужно описывать в мэйн активити.
Оказалось все проще. Невнимательность как всегда.

android:theme=»@style/TextAppearance.AppCompat.Body1″ меняем на android:textAppearance=»@style/TextAppearance.AppCompat.Body1″ и все работает. Спасибо что направили куда капать.



0



There are multiple reasons why this error can occur. Check the following and make sure they are proper:

  • Check your code for drawable and color resources used inside the com.google.android.material.navigation.NavigationView you’ve used, probably in activity_main.xml, if you’re using the default Navigation Drawer template code from Android Studio.
  • Check that the drawable files are in res/drawable folder, not in res/drawable-v21.
  • Check if you’ve used android:backgroundTint() or android:src or similar inside your NavigationView. Since they don’t work below android API Level 21, use app:backgroundTint or app:srcCompat instead.

In my case the problem was the theme value in the Manifest file

<activity
        android:name=".ui.BarcodeReaderDrawerActivity"
        android:label="@string/title_activity_barcode_reader_drawer">
        android:theme="@style/AppBaseTheme.NoActionBar"
    </activity>

Changed in

<activity
        android:name=".ui.BarcodeReaderDrawerActivity"
        android:label="@string/title_activity_barcode_reader_drawer"
        android:theme="@style/Theme.MaterialComponents.Light.NoActionBar">
    </activity>

Tags:

Android

Android Navigationview

Androidx

Related

I’m new to the environment of android studio and the truth is that as I’ve been interacting with the environment I’ve had many mistakes. I have version 4.1 of the android and I tried to go to File HCFCSettting.Build, Execution, Deployment, but I don’t see Intant Run. And he also tries to clean the project and reconstruct it.

introducir la descripción de la imagen aquí

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.project.turisteandoapp, PID: 24919
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.project.turisteandoapp/com.project.turisteandoapp.MainActivity}: android.view.InflateException: Binary XML file line #16: Binary XML file line #16: Error inflating class com.google.android.material.navigation.NavigationView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2907)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2986)
        at android.app.ActivityThread.-wrap11(Unknown Source:0)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1641)
        at android.os.Handler.dispatchMessage(Handler.java:105)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6694)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:769)
     Caused by: android.view.InflateException: Binary XML file line #16: Binary XML file line #16: Error inflating class com.google.android.material.navigation.NavigationView
     Caused by: android.view.InflateException: Binary XML file line #16: Error inflating class com.google.android.material.navigation.NavigationView
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:334)
        at android.view.LayoutInflater.createView(LayoutInflater.java:647)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:790)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:730)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:863)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:824)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)

I see a mistake on the NavigationView, I haven’t touched it for now and I don’t know how to fix it.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="@dimen/nav_header_height"
android:background="@color/purple_700"
android:gravity="bottom"
android:orientation="vertical"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:theme="@style/ThemeOverlay.AppCompat.Dark">
&lt;ImageView
    android:id="@+id/imageView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:contentDescription="@string/nav_header_desc"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    app:srcCompat="@mipmap/ic_launcher_round" /&gt;

&lt;TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/nav_header_vertical_spacing"
    android:text="@string/nav_header_title"
    android:textAppearance="@style/TextAppearance.AppCompat.Body1" /&gt;

&lt;TextViewq
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/nav_header_subtitle" /&gt;

</LinearLayout>

#android #kotlin

Вопрос:

Недавно я начал разработку Kotlin и Android и хочу создать приложение, которое показывало бы рекламу по продаже автомобилей. Но, к сожалению, когда я запускаю это приложение на своем телефоне, оно сразу же выходит из строя. Таким образом, основная функция этого приложения-показать автомобили, которые продаются, и вы, как пользователь, сможете добавлять больше автомобилей в продажу и показывать их, а также бронировать автомобиль и показывать только зарезервированные автомобили. Вот мой код

 package com.example.autooglas

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.appcompat.app.ActionBar
import androidx.fragment.app.Fragment
import com.google.android.material.bottomnavigation.BottomNavigationView

class MainActivity : AppCompatActivity() {
    lateinit var toolbar: ActionBar
    private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener{ item ->
        when (item.itemId){
            R.id.navigation_oglasi -> {
                toolbar.title="Oglasi"
                val oglasiFragment=OglasiFragment.newInstance()
                openFragment(oglasiFragment)
                return@OnNavigationItemSelectedListener true

            }
            R.id.navigation_dodaj_oglas ->{
                toolbar.title = "Dodaj Oglas"
                val dodajOglas = DodajOglasFragment.newInstance()
                openFragment(dodajOglas)
                return@OnNavigationItemSelectedListener true
            }
        }
        false

    }

    private fun openFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.container, fragment)
        transaction.addToBackStack(null)
        transaction.commit()
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        toolbar = supportActionBar!!
        val bottomNavigationView:BottomNavigationView = findViewById(R.id.navigationView)
        bottomNavigationView.setOnNavigationItemSelectedListener ( mOnNavigationItemSelectedListener )
        openFragment(OglasiFragment.newInstance())
    }
}
 

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <FrameLayout
        android:id="@ id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:visibility="visible"
        tools:layout_editor_absoluteX="0dp"
        tools:layout_editor_absoluteY="37dp"
        tools:visibility="visible" />

    <com.google.android.material.bottomnavigation.BottomNavigationView
        android:id="@ id/navigationView"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:background="?android:attr/windowBackground"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:menu="@menu/navigation"
        tools:ignore="MissingClass" />

</androidx.constraintlayout.widget.ConstraintLayout>

 

And her is my Logcat

 19119-19119/com.example.autooglas E/ample.autoogla: [qarth_debug:]  get PatchStore::createDisableExceptionQarthFile method fail.
19119-19119/com.example.autooglas E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.autooglas, PID: 19119
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.autooglas/com.example.autooglas.MainActivity}: android.view.InflateException: Binary XML file line #18: Binary XML file line #18: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3430)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
        at android.os.Handler.dispatchMessage(Handler.java:112)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
     Caused by: android.view.InflateException: Binary XML file line #18: Binary XML file line #18: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
     Caused by: android.view.InflateException: Binary XML file line #18: Error inflating class com.google.android.material.bottomnavigation.BottomNavigationView
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
        at android.view.LayoutInflater.createView(LayoutInflater.java:658)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:801)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:741)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:874)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:835)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:515)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:696)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:170)
        at com.example.autooglas.MainActivity.onCreate(MainActivity.kt:39)
        at android.app.Activity.performCreate(Activity.java:7458)
        at android.app.Activity.performCreate(Activity.java:7448)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1286)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3409)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3614)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:86)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2199)
        at android.os.Handler.dispatchMessage(Handler.java:112)
        at android.os.Looper.loop(Looper.java:216)
        at android.app.ActivityThread.main(ActivityThread.java:7625)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:524)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:987)
     Caused by: java.lang.UnsupportedOperationException: BottomNavigationView does not support submenus
        at com.google.android.material.bottomnavigation.BottomNavigationMenu.addSubMenu(BottomNavigationMenu.java:41)
        at androidx.appcompat.view.SupportMenuInflater$MenuState.addSubMenuItem(SupportMenuInflater.java:536)
19119-19119/com.example.autooglas E/AndroidRuntime:     at androidx.appcompat.view.SupportMenuInflater.parseMenu(SupportMenuInflater.java:182)
        at androidx.appcompat.view.SupportMenuInflater.inflate(SupportMenuInflater.java:129)
        at com.google.android.material.bottomnavigation.BottomNavigationView.inflateMenu(BottomNavigationView.java:347)
        at com.google.android.material.bottomnavigation.BottomNavigationView.<init>(BottomNavigationView.java:223)
        at com.google.android.material.bottomnavigation.BottomNavigationView.<init>(BottomNavigationView.java:131)
            ... 28 more
19119-19119/com.example.autooglas I/Process: Sending signal. PID: 19119 SIG: 9

 

navigation.xml

 <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@ id/navigation_oglasi"
        android:icon="@drawable/ic_reorder_24px"
        android:title="@string/prikazOglasa"
        />
    <item
        android:id="@ id/navigation_rezervisani"
        android:icon="@drawable/ic_reorder_24px"
        android:title="@string/rezervOglas"
        />

    <item
        android:id="@ id/navigation_dodaj_oglas"
        android:icon="@drawable/ic_add_box_24px"
        android:title="@string/dodajOglas"
        />

    <menu />
</menu>
 

Комментарии:

1. Похоже, вам не хватает библиотеки для BottomNaviagationView, и вы подавили ошибку, с помощью tools:ignore="MissingClass" которой она смогла скомпилироваться, несмотря на отсутствие библиотеки. Удалите это и добавьте библиотеку .

2. Я добавил реализацию библиотеки » com.google.android.материал:материал:<версия>», и проблема все еще существует.

3. замените версию на последнюю версию, как это implementation 'com.google.android.material:material:1.3.0'

4. Делает ли ваш navigtation.xml есть подменю (вложенные меню)?

5. я добавил navigation.xml так что вы можете видеть

Ответ №1:

Вызвано: java.lang.Исключение UnsupportedOperationException: BottomNavigationView не поддерживает подменю

В вашем меню в конце вашего меню есть подменю, просто удалите его, и оно должно работать

 <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@ id/navigation_oglasi"
        android:icon="@drawable/ic_reorder_24px"
        android:title="@string/prikazOglasa"
        />
    <item
        android:id="@ id/navigation_rezervisani"
        android:icon="@drawable/ic_reorder_24px"
        android:title="@string/rezervOglas"
        />

    <item
        android:id="@ id/navigation_dodaj_oglas"
        android:icon="@drawable/ic_add_box_24px"
        android:title="@string/dodajOglas"
        />

   <!-- Remove this line  <menu /> -->

</menu>
 
Posted By: Anonymous

I followed a tutorial of new component NavigationView in Support Design Library and can’t get through this error message :

Error inflating class android.support.design.widget.NavigationView

I tried every workaround here

Error when using any Android Design Support Library Elements

but error message still exists.

xml

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true" >
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

    <include layout="@layout/toolbar" android:id="@+id/mainToolBar" />

    <fragment android:name="com.ais.cherry.fragment.LoginFragment"
        android:id="@+id/loginFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/mainToolBar" />
    <fragment     android:name="com.ais.cherry.fragment.WaterFallFragment"
        android:id="@+id/mainFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/mainToolBar" />
    <fragment android:name="com.ais.cherry.fragment.SearchFragment"
        android:id="@+id/searchFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/mainToolBar" />
    <fragment android:name="com.ais.cherry.fragment.ChatMainFragment"
        android:id="@+id/chatMainFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/mainToolBar" />
    <fragment android:name="com.ais.cherry.fragment.ProfileFragment"
        android:id="@+id/profileFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/mainToolBar" />


    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@android:color/white"
        app:itemTextColor="#212121"
        app:headerLayout="@layout/drawer_header"
        app:menu="@menu/drawer" />
</android.support.v4.widget.DrawerLayout>

build.gradle

buildscript {
    repositories {
        mavenCentral()
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
        classpath 'com.android.tools.build:gradle:1.2.3'
    }
}

compileSdkVersion 22
buildToolsVersion "22.0.1"

defaultConfig {
    applicationId "com.ais.cherry"
    minSdkVersion 16
    targetSdkVersion 22      
    multiDexEnabled true
    renderscriptTargetApi 22
    renderscriptSupportModeEnabled true

}
dependencies {
    compile 'com.android.support:appcompat-v7:22.2.0'
    compile 'com.android.support:support-v4:22.2.0'
    compile 'com.android.support:design:22.2.0'
    compile 'com.android.support:recyclerview-v7:22.2.0'
}

Project build.gradle

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'
    }
}

styles.xml

<?xml version="1.0" encoding="utf-8"?>
<!-- Base application theme. -->
<style name="AppTheme" parent="AppTheme.Base">

</style>

<style name="AppTheme.Base" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowActionBarOverlay">true</item>
    <item name="android:windowActionModeOverlay">true</item>
    <item name="android:actionModeStyle">@style/AppTheme.ActionModeStyle</item>
    <item name="android:windowActionBar">false</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="android:windowNoTitle">true</item>
    <!-- Support library compatibility -->
    <item name="windowActionBarOverlay">true</item>

    <!-- ActionBar color -->
    <item name="colorPrimary">#E91E63</item>
    <!-- Status bar color -->
    <item name="colorPrimaryDark">#C2185B</item>
    <!-- Window color -->
    <item name="android:windowBackground">@color/white</item>
    <!-- ActionBar title text -->
    <item name="android:titleTextStyle">@style/AppTheme.MyActionBarTitleText</item>

    <item name="colorAccent">#9E9E9E</item>

    <item name="drawerArrowStyle">@style/AppTheme.MyDrawerArrowStyle</item>

    <!-- color for actionMenu-->
    <item name="actionMenuTextColor">#FFFFFF</item>
    <item name="android:actionMenuTextColor">#FFFFFF</item>
    <!-- android:textColorSecondary is the color of the menu
   overflow icon (three vertical dots) -->
    <item name="android:textColorPrimary">#212121</item>
    <item name="android:textColorSecondary">#FFFFFF</item>
    <!--Navigation bar color-->
    <item name="android:navigationBarColor">#E91E63</item>
    <!--Status bar color-->
    <item name="android:statusBarColor">#C2185B</item>
</style>

Any help would be appreciated!

Edit — add @menu/drawer & @menu/drawer_header & stacktrace

drawer.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/nav_first_fragment"
            android:icon="@drawable/home_view"
            android:checked="true"
            android:title="@string/main"/>
        <item
            android:id="@+id/nav_second_fragment"
            android:icon="@drawable/comment_view"
            android:title="@string/chat"/>
        <item
            android:id="@+id/nav_third_fragment"
            android:icon="@drawable/user_view"
            android:title="@string/profile"/>
        <item android:title="@string/search">
            <menu>
                <item
                    android:title="@string/clothes"/>
                <item
                    android:title="@string/pants"/>
            </menu>
        </item>
    </group>
</menu>

drawer_header.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="192dp"
    android:background="?attr/colorPrimaryDark"
    android:padding="16dp"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:gravity="bottom">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/title"
        android:textColor="@android:color/white"
            android:textAppearance="@style/TextAppearance.AppCompat.Body1"/>
</LinearLayout>

StackTrace (only part of them)

It thrown out three exceptions as below : all points out that the problems is caused by the line of “setContentView(layout)” at in layout.xml.

java.lang.RuntimeException: Unable to start activity  ComponentInfo{com.ais.cherry/com.ais.cherry.activity.FirstActivity}:    android.view.InflateException: Binary XML file line #32: Error inflating    class android.support.design.widget.NavigationView

Caused by: android.view.InflateException: Binary XML file line #32: Error inflating class android.support.design.widget.NavigationView

Caused by: java.lang.reflect.InvocationTargetException

Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x0

Solution

Actually it is not the matter of the primarycolortext, upgrading or downgrading the dependencies.This problem will likely occur when the version of your appcompat library and design support library doesn’t match.

Example of matching condition

compile 'com.android.support:appcompat-v7:23.1.1' // appcompat library
compile 'com.android.support:design:23.1.1'       //design support library
Answered By: Anonymous

Related Articles

  • MaterialCardView is in front of NavigationView. How can I…
  • Navigation View and Constraint Layout
  • How to implement HorizontalScrollView like Gallery?
  • Android Layout Animations from bottom to top and top to…
  • Same Navigation Drawer in different Activities
  • Error inflating class android.support.v7.widget.Toolbar?
  • Creating a SearchView that looks like the material design…
  • Convert xml without namespaces
  • Fragment not showing properly
  • Failed to load AppCompat ActionBar with unknown error in…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Понравилась статья? Поделить с друзьями:
  • Error inflating class com google android material appbar appbarlayout
  • Error inflating class com google ads adview
  • Error inflating class androidx fragment app fragmentcontainerview
  • Error inflate data stream error unknown compression method
  • Error inflate data stream error incorrect header check