Как исправить ошибку раздувания FloatingActionButton в androidx для API версии 23?

Я использую androidx для создания базового приложения каталога. Использование FloatingActionButton для добавления записей. Приложение отлично работает на эмуляторе, но при запуске на моем мобильном устройстве отображается исключение android.view.InflateException.

Ошибка -

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.vestige.directory2, PID: 10648
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.vestige.directory2/com.vestige.directory2.Activities.MainActivity}: android.view.InflateException: Binary XML file line #26: Binary XML file line #26: Error inflating class com.google.android.material.floatingactionbutton.FloatingActionButton
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2545)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2605)
        at android.app.ActivityThread.access$1100(ActivityThread.java:165)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:179)
        at android.app.ActivityThread.main(ActivityThread.java:5730)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681)
     Caused by: android.view.InflateException: Binary XML file line #26: Binary XML file line #26: Error inflating class com.google.android.material.floatingactionbutton.FloatingActionButton
        at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
        at android.view.LayoutInflater.inflate(LayoutInflater.java:374)
        at androidx.appcompat.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
        at com.vestige.directory2.Activities.MainActivity.onCreate(MainActivity.java:51)
        at android.app.Activity.performCreate(Activity.java:6439)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2498)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2605) 
        at android.app.ActivityThread.access$1100(ActivityThread.java:165) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:179) 
        at android.app.ActivityThread.main(ActivityThread.java:5730) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681) 
     Caused by: android.view.InflateException: Binary XML file line #26: Error inflating class com.google.android.material.floatingactionbutton.FloatingActionButton
        at android.view.LayoutInflater.createView(LayoutInflater.java:645)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:835)
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798)
        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:469) 
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
        at com.vestige.directory2.Activities.MainActivity.onCreate(MainActivity.java:51) 
        at android.app.Activity.performCreate(Activity.java:6439) 
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2498) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2605) 
        at android.app.ActivityThread.access$1100(ActivityThread.java:165) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:179) 
        at android.app.ActivityThread.main(ActivityThread.java:5730) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681) 
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance(Native Method)
        at android.view.LayoutInflater.createView(LayoutInflater.java:619)
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764) 
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:835) 
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) 
        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:469) 
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
        at com.vestige.directory2.Activities.MainActivity.onCreate(MainActivity.java:51) 
        at android.app.Activity.performCreate(Activity.java:6439) 
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2498) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2605) 
        at android.app.ActivityThread.access$1100(ActivityThread.java:165) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:179) 
        at android.app.ActivityThread.main(ActivityThread.java:5730) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681) 
     Caused by: android.content.res.Resources$NotFoundException: Resource "com.vestige.directory2:drawable/ic_plus_white" (7f07006b) is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f07006b a=-1 r=0x7f07006b}
        at android.content.res.Resources.loadDrawableForCookie(Resources.java:2798)
        at android.content.res.Resources.loadDrawable(Resources.java:2732)
        at android.content.res.TypedArray.getDrawable(TypedArray.java:870)
        at android.widget.ImageView.<init>(ImageView.java:152)
        at android.widget.ImageButton.<init>(ImageButton.java:84)
        at android.widget.ImageButton.<init>(ImageButton.java:80)
        at com.google.android.material.internal.VisibilityAwareImageButton.<init>(VisibilityAwareImageButton.java:45)
        at com.google.android.material.floatingactionbutton.FloatingActionButton.<init>(FloatingActionButton.java:192)
        at com.google.android.material.floatingactionbutton.FloatingActionButton.<init>(FloatingActionButton.java:188)
        at java.lang.reflect.Constructor.newInstance(Native Method) 
        at android.view.LayoutInflater.createView(LayoutInflater.java:619) 
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:764) 
        at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704) 
        at android.view.LayoutInflater.rInflate(LayoutInflater.java:835) 
        at android.view.LayoutInflater.rInflateChildren(LayoutInflater.java:798) 
        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:469) 
        at androidx.appcompat.app.AppCompatActivity.setContentView(AppCompatActivity.java:140) 
        at com.vestige.directory2.Activities.MainActivity.onCreate(MainActivity.java:51) 
        at android.app.Activity.performCreate(Activity.java:6439) 
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1108) 
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2498) 
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2605) 
        at android.app.ActivityThread.access$1100(ActivityThread.java:165) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1473) 
        at android.os.Handler.dispatchMessage(Handler.java:102) 
        at android.os.Looper.loop(Looper.java:179) 
        at android.app.ActivityThread.main(ActivityThread.java:5730) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:791) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:681) 

FloatingActionButton XML (этот код взят из строки 26, как и в ошибке.) -

 <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id = "@+id/fab"
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:layout_gravity = "bottom|end"
        android:layout_margin = "@dimen/fab_margin"
        android:src = "@drawable/ic_plus_white" />

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

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = findViewById(R.id.fab);

        fab.setOnClickListener(v -> addInformation());

Я упомянул много решений, и в основном все они говорят об изменении android:backgroundTint на app:backgroundTint, который, как вы можете видеть, я даже не использую.

Мои build.gradle(Module: app) зависимости -

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.2'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'com.google.android.material:material:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test:runner:1.2.0'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
    // Room components
    implementation "androidx.room:room-runtime:$rootProject.roomVersion"
    annotationProcessor "androidx.room:room-compiler:$rootProject.roomVersion"
    androidTestImplementation "androidx.room:room-testing:$rootProject.roomVersion"

    // Lifecycle components
    implementation "androidx.lifecycle:lifecycle-extensions:$rootProject.archLifecycleVersion"
    annotationProcessor "androidx.lifecycle:lifecycle-compiler:$rootProject.archLifecycleVersion"

    //Gson
    implementation 'com.google.code.gson:gson:2.8.5'
}

Мои стили.xml -

<resources>

    <!-- Base application theme. -->
    <style name = "AppTheme" parent = "Theme.MaterialComponents.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name = "colorPrimary">@color/colorPrimary</item>
        <item name = "colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name = "colorAccent">@color/colorAccent</item>
    </style>

    <style name = "AppTheme.NoActionBar">
        <item name = "windowActionBar">false</item>
        <item name = "windowNoTitle">true</item>
    </style>

    <style name = "AppTheme.AppBarOverlay" parent = "ThemeOverlay.MaterialComponents.Dark.ActionBar" />

    <style name = "AppTheme.PopupOverlay" parent = "ThemeOverlay.MaterialComponents.Light" />

</resources>

ic_plus_white.xml -

<vector android:height = "23dp"
    android:viewportHeight = "512"
    android:viewportWidth = "448"
    android:width = "20dp"
    xmlns:android = "http://schemas.android.com/apk/res/android">
    <path
        android:fillColor = "#FFF"
        android:pathData = "M416,208H272V64c0,-17.67 -14.33,-32 -32,-32h-32c-17.67,0 -32,14.33 -32,32v144H32c-17.67,0 -32,14.33 -32,32v32c0,17.67 14.33,32 32,32h144v144c0,17.67 14.33,32 32,32h32c17.67,0 32,-14.33 32,-32V304h144c17.67,0 32,-14.33 32,-32v-32c0,-17.67 -14.33,-32 -32,-32z" />
</vector>

Версия API на эмуляторе 28

Версия API для мобильных устройств 23

РЕШЕНО: Просто нужно было переместить мой drawable ic_plus_white.xml из папки drawable-v-24 в папку drawable. Решил проблему!

Вы просто спасли мой день :)

Junior 29.05.2021 10:57
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
Как вычислять биты и понимать побитовые операторы в Java - объяснение с примерами
В компьютерном программировании биты играют важнейшую роль в представлении и манипулировании данными на двоичном уровне. Побитовые операции...
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Поднятие тревоги для долго выполняющихся методов в Spring Boot
Приходилось ли вам сталкиваться с требованиями, в которых вас могли попросить поднять тревогу или выдать ошибку, когда метод Java занимает больше...
Полный курс Java для разработчиков веб-сайтов и приложений
Полный курс Java для разработчиков веб-сайтов и приложений
Получите сертификат Java Web и Application Developer, используя наш курс.
4
1
1 171
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Ответ принят как подходящий

Убедитесь, что ваше приложение или тема активности наследует одну из следующих тем:

  • Theme.MaterialComponents
  • Theme.MaterialComponents.NoActionBar
  • Theme.MaterialComponents.Light
  • Theme.MaterialComponents.Light.NoActionBar
  • Theme.MaterialComponents.Light.DarkActionBar
  • Theme.MaterialComponents.DayNight
  • Theme.MaterialComponents.DayNight.NoActionBar
  • Theme.MaterialComponents.DayNight.DarkActionBar

Кажется, ваш drawable/ic_plus_white недействителен. Пожалуйста, проверьте его содержимое.

Я обновил вопрос своим styles.xml, и я думаю, что тоже это сделал.

Mihir Srivastava 06.07.2019 15:56

как насчет drawable/ic_plus_white? Можете ли вы поделиться этим тоже?

Deˣ 06.07.2019 16:03

да ладно, я обновлю вопрос с этим? Но я не знаю, может ли это быть причиной ошибки, поскольку это просто векторный актив.

Mihir Srivastava 06.07.2019 20:26

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

Deˣ 06.07.2019 20:34

Спасибо что решили проблему!! Мое рисование было в папке drawable-v-24, и я переместил его в папку drawable. Работает как шарм! Спасибо еще раз

Mihir Srivastava 06.07.2019 20:48

Проблема, с которой вы столкнулись, находится в строке 26 XML-файла активности запуска. если вы можете показать нам этот файл, мы можем помочь.

FloatingActionButton xml — это xml-код из строки 26 моего main_activity.xml

Mihir Srivastava 06.07.2019 20:15

Другие вопросы по теме