Error inflating class com google android material button materialbutton

What i'm trying to achieve is having a gridview with some materialButton inside. I tried to create the gridview like : <GridView android:id="@+id/login_gridview_code_input"...

What i’m trying to achieve is having a gridview with some materialButton inside.
I tried to create the gridview like :

<GridView
            android:id="@+id/login_gridview_code_input"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:numColumns="3"
            android:horizontalSpacing="15dp"
            android:verticalSpacing="15dp">
        </GridView>

And the element to be inflated like:

<?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"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

        <com.google.android.material.button.MaterialButton
            android:id="@+id/button_code_digit"
            style="@style/Widget.MaterialComponents.Button.OutlinedButton.Icon"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:insetLeft="0dp"
            android:insetTop="0dp"
            android:insetRight="0dp"
            android:insetBottom="0dp"
            android:padding="0dp"
            app:iconGravity="textStart"
            app:iconPadding="0dp"
            app:iconSize="40dp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:shapeAppearanceOverlay="@style/ShapeAppearanceOverlay.pswStorer.Button.Circle" />

</androidx.constraintlayout.widget.ConstraintLayout>

the adapter inflates the button :

inflter = (LayoutInflater.from(applicationContext)); 
view = inflter.inflate(R.layout.button_code, null); // inflate the layout

but I always receive this stacktrace :

Error inflating class com.google.android.material.button.MaterialButton
Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.MaterialComponents (or a descendant).

I checked the appTheme but seems correct to me:

<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="materialAlertDialogTheme">@style/AlertDialogMaterialTheme</item>
    </style>

Any ideas?

EDIT: I tried to check and my app has the correct theme

android:theme="@style/AppTheme"

I also changed the theme to Theme.MaterialComponents.DayNight.NoActionBar.Bridge but nothing changed

Hi everyone.

I’m trying to dynamically inflate a button layout into a recycler view item from my item adapter.
Here is how it looks :

LayoutInflater factory = LayoutInflater.from(mContext); View buttonView = factory.inflate(buttonsList.get(position).getLayout(), null); holder.buttonContainer.addView(buttonView);

Basically, my getLayout attribute returns the layout id of the corresponding button item.

Layout looks like this :

<com.google.android.material.button.MaterialButton xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/material_button" style="@style/Widget.MaterialComponents.Button" android:layout_width="match_parent" android:layout_height="wrap_content" android:backgroundTint="@color/colorPrimary" android:text="Search" android:textSize="14sp" android:textAllCaps="true" android:fontFamily="@font/raleway_semibold" />

I can inflate basic buttons from the old AppCompat library, but not from the Material Design.

I get the following error :

android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class com.google.android.material.button.MaterialButton
    Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class com.google.android.material.button.MaterialButton

Do you have any idea where the problem comes from ? Is it a library bug ?

Thanks in advance,

Corentin

What’s the problem? The button has been implemented as MaterialButton. All the necessary libraries and styles are connected.

<com.google.android.material.button.MaterialButton
            android:id="@+id/Find"
            style="@style/Widget.MaterialComponents.Button.OutlinedButton"            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Find"
            android:textSize="12dp"
            android:onClick="Find"/>

gradle

 compile group: 'com.google.android.material', name: 'material', version: '1.1.0-alpha05'
compile group: 'com.android.support', name: 'design', version: '28.0.0'

compile group: 'com.android.support', name: 'appcompat-v7', version: '28.0.0'

Steel

<style name="Widget.MaterialComponents.Button" parent="Widget.AppCompat.Button">
<item name="enforceMaterialTheme">true</item>
<item name="enforceTextAppearance">true</item>
<item name="android:textAppearance">?attr/textAppearanceButton</item>
<item name="android:textColor">@color/mtrl_btn_text_color_selector</item>
<item name="android:paddingLeft">@dimen/mtrl_btn_padding_left</item>
<item name="android:paddingRight">@dimen/mtrl_btn_padding_right</item>
<item name="android:paddingTop">@dimen/mtrl_btn_padding_top</item>
<item name="android:paddingBottom">@dimen/mtrl_btn_padding_bottom</item>
<item name="android:insetLeft">0dp</item>
<item name="android:insetRight">0dp</item>
<item name="android:insetTop">@dimen/mtrl_btn_inset</item>
<item name="android:insetBottom">@dimen/mtrl_btn_inset</item>
<item name="android:stateListAnimator" tools:ignore="NewApi">@animator/mtrl_btn_state_list_anim</item>
<item name="cornerRadius">@null</item>
<item name="elevation">@dimen/mtrl_btn_elevation</item>
<item name="iconPadding">@dimen/mtrl_btn_icon_padding</item>
<item name="iconTint">@color/mtrl_btn_text_color_selector</item>
<item name="rippleColor">@color/mtrl_btn_ripple_color</item>
<item name="backgroundTint">@color/mtrl_btn_bg_color_selector</item>
<item name="shapeAppearance">?attr/shapeAppearanceSmallComponent</item>
</style>
<style name="Widget.MaterialComponents.Button.OutlinedButton" parent="Widget.MaterialComponents.Button.TextButton">
<item name="android:paddingLeft">@dimen/mtrl_btn_padding_left</item>
<item name="android:paddingRight">@dimen/mtrl_btn_padding_right</item>
<item name="strokeColor">@color/mtrl_btn_stroke_color_selector</item>
<item name="strokeWidth">@dimen/mtrl_btn_stroke_size</item>
</style>

Я пытаюсь использовать кодовую метку MDC на codelabs.developers.google.com с последними версиями библиотеки. EditTextandroid.support.design.widget.TextInputEditText кажется, работает должным образом, однако при использовании android.support.design.button.MaterialButton создается исключение InflateException во время выполнения.

Конфигурация Gradle:

compileSdkVersion 28

minSdkVersion 21

targetSdkVersion 28

dependencies {
   def lifecycle_version = "1.1.1"
   def nav_version = "1.0.0-alpha05"
   def work_version = "1.0.0-alpha06"
   def supportLibraryVersion = "28.0.0-rc01"

   implementation fileTree(include: ['*.jar'], dir: 'libs')
   api "android.arch.lifecycle:extensions:$lifecycle_version"
   api "android.arch.lifecycle:common-java8:$lifecycle_version"
   api "android.arch.navigation:navigation-fragment:$nav_version"
   api "android.arch.navigation:navigation-ui:$nav_version"
   api "android.arch.work:work-runtime:$work_version"

   api ("com.android.support:appcompat-v7:$supportLibraryVersion", {
       exclude group: 'com.android.support', module: 'support-media-compat'
   })
   api ("com.android.support:design:$supportLibraryVersion", {
       exclude group: 'com.android.support', module: 'support-media-compat'
   })
   api ("com.android.support:cardview-v7:$supportLibraryVersion", {
       exclude group: 'com.android.support', module: 'support-media-compat'
   })
   api ("com.android.support:customtabs:$supportLibraryVersion", {
       exclude group: 'com.android.support', module: 'support-media-compat'
   })

Трассировки стека

    E/XXXXXXApp: Unhandled Exception - Application Crash
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.XXXXXX/com.XXXXXX.activities.XXXXXXActivity}: android.view.InflateException: Binary XML file line #84: Binary XML file line #84: Error inflating class android.support.design.button.MaterialButton
    at com.XXXXXXActivity.onCreate(LoginActivity.java:107)
...

 Caused by: java.lang.IllegalArgumentException: This component requires that you specify a valid TextAppearance attribute. Update your app theme to inherit from Theme.MaterialComponents (or a descendant).
                 at android.support.design.internal.ThemeEnforcement.checkTextAppearance(ThemeEnforcement.java:170)
                 at android.support.design.internal.ThemeEnforcement.obtainStyledAttributes(ThemeEnforcement.java:75)
                 at android.support.design.button.MaterialButton.<init>(MaterialButton.java:140)
                 at android.support.design.button.MaterialButton.<init>(MaterialButton.java:133)

РЕДАКТИРОВАТЬ: добавил больше деталей в stacktrace и выяснил, что проблема была в том, что тема приложения должна быть унаследована от Theme.MaterialComponents.

Я нахожусь в процессе замены кнопок в моем приложении Материальными кнопками, используя <com.google.android.material.button.MaterialButton в файле XML и private MaterialButton dateButton; в файле фрагмента Java. Я изучал лабораторию кода «MDC-101 Android: компоненты материалов (MDC) Основы (Java) «, чтобы увидеть, как используется кнопка Материал. В файле gradle.build (Module: app) я добавил зависимости, как в кодовой лаборатории. Лаборатория кода компилируется и работает нормально. Мое приложение компилируется нормально, но выдает ошибку при надувании макета фрагмента:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: nl.kl_solutions.schedulecompareforzermelo, PID: 16708
              android.view.InflateException: Binary XML file line #26: Binary XML file line #26: Error inflating class com.google.android.material.button.MaterialButton
              Caused by: android.view.InflateException: Binary XML file line #26: Error inflating class com.google.android.material.button.MaterialButton
              Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.material.button.MaterialButton" on path: DexPathList[[zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/base.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_dependencies_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_resources_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_0_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_1_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_2_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_3_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_4_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_5_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_6_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_7_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_8_apk.apk", zip file "/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/split_lib_slice_9_apk.apk"],nativeLibraryDirectories=[/data/app/nl.kl_solutions.schedulecompareforzermelo-o6fuvqQPirym08EhaTRI6Q==/lib/x86_64, /system/lib64]]
                  at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)

Это фрагмент из моего файла макета:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:background="@color/primaryLightColor"
    android:paddingLeft="@dimen/rasterleftpadding"
    android:paddingRight="@dimen/rasterrightpadding" >

    <Button
        android:id="@+id/btn_previous"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_gravity="left"
        android:text="prev" />

    <com.google.android.material.button.MaterialButton
        android:id="@+id/btn_week"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_weight="1"
         />

    <Button
        android:id="@+id/btn_next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:layout_weight="1"
        android:text="next" />

</LinearLayout>

А вот фрагмент из onCreateView:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View fragmentLayout = inflater.inflate(R.layout.fragment_week_schedule, container, false);
    //get references to the buttonBar buttons.
    leftButton = fragmentLayout.findViewById(R.id.btn_previous);
    rightButton = fragmentLayout.findViewById(R.id.btn_next);
    dateButton = fragmentLayout.findViewById(R.id.btn_week);

Я только изменил кнопку даты на кнопку «Материал», которая дает мне ошибку. Приложение работает нормально при использовании обычной кнопки для dateButton.

Это мой файл gradle.build:

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "com.android.support:appcompat-v7:$rootProject.supportVersion"
implementation "com.android.support:preference-v7:$rootProject.supportVersion"
implementation "com.android.support:recyclerview-v7:$rootProject.supportVersion"
implementation "com.android.support:cardview-v7:$rootProject.supportVersion"
implementation "com.android.support.constraint:constraint-layout:1.1.3"
implementation "com.android.support:design:$rootProject.supportVersion"
implementation "com.android.support:support-v4:$rootProject.supportVersion"
implementation 'com.google.code.gson:gson:2.8.5'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'

//database components
implementation "android.arch.persistence.room:runtime:$rootProject.roomVersion"
annotationProcessor "android.arch.persistence.room:compiler:$rootProject.roomVersion"

// Lifecycle components
implementation "android.arch.lifecycle:extensions:$rootProject.archLifecycleVersion"
annotationProcessor "android.arch.lifecycle:compiler:$rootProject.archLifecycleVersion"
//QR library
implementation 'me.dm7.barcodescanner:zxing:1.9.8'

Где $ rootProject.supportVersion — 28.0.0-бета01. Я знаю, что rc-01 и rc02 для некоторых библиотек доступны, но я запустил лабораторию кода с зависимостями beta01, поэтому решил сохранить эту версию, чтобы минимизировать изменения.

Кто-нибудь знает, что вызывает ошибку во время выполнения?

4 ответа

Лучший ответ

Как подсказывает ЗДЕСЬ, вы должны добавить зависимость в свой build.gradle:

implementation 'com.google.android.material:material:1.0.0-beta01'

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

<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light">
<!-- ... -->

Если вы не можете изменить свою тему для наследования от темы Компоненты материала, вы можете наследовать от темы Мост компонентов.

<style name="Theme.MyApp" parent="Theme.MaterialComponents.Light.Bridge">
<!-- ... -->

Как сказал Рейске:

Обратите внимание, что это сейчас не бета! Таким образом, вы можете использовать реализацию 'com.google.android.material:material:1.0.0'


52

Skenia
25 Сен 2018 в 19:06

Попробуйте обновить тему приложения, чтобы она наследовала от Theme.MaterialComponents (или потомка)


2

Iman Marashi
2 Дек 2019 в 17:31

На мой взгляд, лучший выбор — создать отдельный собственный стиль для кнопки материала, где она расширяет тему материала:

<style name="MatButton" parent="Theme.MaterialComponents">
    <item name="colorOnPrimary">@android:color/holo_red_light</item>
    <item name="colorPrimary">@android:color/holo_orange_dark</item>
    <item name="colorOnSurface">@android:color/holo_orange_light</item>
</style>

<com.google.android.material.button.MaterialButton
    android:id="@+id/searchBtn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Search"
    android:textColor="@android:color/white"
    android:textAppearance="@style/TextAppearance.MaterialComponents.Button"
    android:theme="@style/MatButton"
    />


6

mr.boyfox
7 Июн 2019 в 20:12

При сбое Следующее сообщение было выведено в Logcat.

Причина: java.lang.IllegalArgumentException: этот компонент требует, чтобы вы указали действительный атрибут TextAppearance. Обновите тему своего приложения, чтобы наследовать от Theme.MaterialComponents (или потомка).

Следовательно, вы также можете отобразить MaterialButton, добавив TextAppearance.

<com.google.android.material.button.MaterialButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@android:string/ok"
    android:textAppearance="@style/TextAppearance.AppCompat.Medium" />


7

Hashido Tomoya
10 Окт 2018 в 08:10

В чем может быть проблема? Кнопка реализована как MaterialButton. Все нужные библиотеки и стили подключены.

<com.google.android.material.button.MaterialButton
            android:id="@+id/Find"
            style="@style/Widget.MaterialComponents.Button.OutlinedButton"            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Find"
            android:textSize="12dp"
            android:onClick="Find"/>

gradle

 compile group: 'com.google.android.material', name: 'material', version: '1.1.0-alpha05'


    compile group: 'com.android.support', name: 'design', version: '28.0.0'

    compile group: 'com.android.support', name: 'appcompat-v7', version: '28.0.0'

Стили

<style name="Widget.MaterialComponents.Button" parent="Widget.AppCompat.Button">
        <item name="enforceMaterialTheme">true</item>
        <item name="enforceTextAppearance">true</item>
        <item name="android:textAppearance">?attr/textAppearanceButton</item>
        <item name="android:textColor">@color/mtrl_btn_text_color_selector</item>
        <item name="android:paddingLeft">@dimen/mtrl_btn_padding_left</item>
        <item name="android:paddingRight">@dimen/mtrl_btn_padding_right</item>
        <item name="android:paddingTop">@dimen/mtrl_btn_padding_top</item>
        <item name="android:paddingBottom">@dimen/mtrl_btn_padding_bottom</item>
        <item name="android:insetLeft">0dp</item>
        <item name="android:insetRight">0dp</item>
        <item name="android:insetTop">@dimen/mtrl_btn_inset</item>
        <item name="android:insetBottom">@dimen/mtrl_btn_inset</item>
        <item name="android:stateListAnimator" tools:ignore="NewApi">@animator/mtrl_btn_state_list_anim</item>
        <item name="cornerRadius">@null</item>
        <item name="elevation">@dimen/mtrl_btn_elevation</item>
        <item name="iconPadding">@dimen/mtrl_btn_icon_padding</item>
        <item name="iconTint">@color/mtrl_btn_text_color_selector</item>
        <item name="rippleColor">@color/mtrl_btn_ripple_color</item>
        <item name="backgroundTint">@color/mtrl_btn_bg_color_selector</item>
        <item name="shapeAppearance">?attr/shapeAppearanceSmallComponent</item>
    </style>
<style name="Widget.MaterialComponents.Button.OutlinedButton" parent="Widget.MaterialComponents.Button.TextButton">
        <item name="android:paddingLeft">@dimen/mtrl_btn_padding_left</item>
        <item name="android:paddingRight">@dimen/mtrl_btn_padding_right</item>
        <item name="strokeColor">@color/mtrl_btn_stroke_color_selector</item>
        <item name="strokeWidth">@dimen/mtrl_btn_stroke_size</item>
    </style>

Hi everyone.

I’m trying to dynamically inflate a button layout into a recycler view item from my item adapter.
Here is how it looks :

LayoutInflater factory = LayoutInflater.from(mContext);
View buttonView = factory.inflate(buttonsList.get(position).getLayout(), null);
holder.buttonContainer.addView(buttonView);

Basically, my getLayout attribute returns the layout id of the corresponding button item.

Layout looks like this :

<com.google.android.material.button.MaterialButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/material_button"
style="@style/Widget.MaterialComponents.Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="@color/colorPrimary"
android:text="Search"
android:textSize="14sp"
android:textAllCaps="true"
android:fontFamily="@font/raleway_semibold" />

I can inflate basic buttons from the old AppCompat library, but not from the Material Design.

I get the following error :

android.view.InflateException: Binary XML file line #2: Binary XML file line #2: Error inflating class com.google.android.material.button.MaterialButton
    Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class com.google.android.material.button.MaterialButton

Do you have any idea where the problem comes from ? Is it a library bug ?

Thanks in advance,

Corentin

All 11 comments

Try to update your app theme to inherit from Theme.MaterialComponents (or a descendant)

@houdayec I faced this issue before and it was because the android:textAppearance attribute was missing.

Just add the below attribute and your problem should be fixed.

android:textAppearance="@style/TextAppearance.MaterialComponents.Button"

@m-Samhoury I had to add yours plus another line to MaterialButton attributes:

android:theme="@style/FormButton"
android:textAppearance="@style/TextAppearance.MaterialComponents.Button"

Had to create my own style

<style name="FormButton" parent="Theme.MaterialComponents">
    <item name="colorOnPrimary">@android:color/holo_red_light</item>
    <item name="colorPrimary">@android:color/holo_orange_dark</item>
    <item name="colorOnSurface">@android:color/holo_orange_light</item>
</style>

Then it worked.

Change your AppTheme parent to Theme.MaterialComponents

Before

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

After

    <!-- Material application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

More

Change your AppTheme parent to Theme.MaterialComponents

Before

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

After

    <!-- Material application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
        <!-- Customize your theme here. -->
    </style>

More

Thank you Twibap
This worked for me

check your style file whether is it define as AppCompa or MaterialComponents.
<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
if it is AppCompat yo are trying material but your global one is set to Material. Thatswhy error is showing

Issue still happening even after setting all the properties commented above. Using com.google.android.material:material:1.1.0

Try to change theme attribute into application node inside manifest file!!!

Changed the style and it works perfectly!
Old =

I have an application with min sdk 16 up to 23. I want to use Material design as much as possible. It also has to be fullscreen app. AppCompat support library is included. Now I have Logon activity with some buttons:

<Button
    android:id="@+id/act_logon_btn_logon"
    style="@style/ButtonDefault"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/act_logon_logon" />

Styles are as follows (values/styles.xml):

<style name="Theme.AppCompat.Light.NoActionBar.FullScreen" parent="@style/Theme.AppCompat.Light">
    <item name="windowNoTitle">true</item>
    <item name="windowActionBar">false</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowContentOverlay">@null</item>
</style>

<style name="AppThemeBase" parent="Theme.AppCompat.Light.NoActionBar.FullScreen"></style>

<style name="AppTheme" parent="AppThemeBase"></style>

<style name="ButtonDefault" parent="Widget.AppCompat.Button">
    <item name="android:textSize">?attr/font_medium</item>
</style>

<style name="FontStyle"></style>

<style name="FontStyle.Small">
    <item name="font_small">12sp</item>
    <item name="font_medium">14sp</item>
    <item name="font_large">16sp</item>
</style>

<style name="FontStyle.Medium">
    <item name="font_small">16sp</item>
    <item name="font_medium">18sp</item>
    <item name="font_large">20sp</item>
</style>

<style name="FontStyle.Large">
    <item name="font_small">20sp</item>
    <item name="font_medium">22sp</item>
    <item name="font_large">24sp</item>
</style>

And in values/attrs:

<declare-styleable name="FontStyle">
    <attr name="font_small" format="dimension" />
    <attr name="font_medium" format="dimension" />
    <attr name="font_large" format="dimension" />
</declare-styleable>

Attribute font_medium is defined as described here. The behavior I don’t understand is that when the Logon activity gets opened, everything is OK, no exceptions. But when I open another activity from Logon activity with fragment inside and the fragment has a button with this style, I get an exception saying «Error inflating class Button». When I delete the textSize attribute from the ButtonDefault style, everything works. Why it does work somewhere and somewhere not? Is there something wrong with the custom attribute?

I’ve tried to create values-v21/styles.xml with that style but without effect.

Can you also please explain differences between following parent style definitions? I’m getting lost.

parent="Widget.AppCompat.Button"
parent="@style/Widget.AppCompat.Button"
parent="android:Widget.Button"
parent="android:Widget.AppCompat.Button"
parent="android:Widget.Material.Button"
parent="android:style/Widget.Material.Button"

Thank you.

EDIT 1 — exception:

12-17 10:56:53.950: E/AndroidRuntime(7251): FATAL EXCEPTION: main
12-17 10:56:53.950: E/AndroidRuntime(7251): Process: test.android, PID: 7251
12-17 10:56:53.950: E/AndroidRuntime(7251): java.lang.RuntimeException: Unable to start activity ComponentInfo{test.dci.android/test.dci.android.view.activity.TransactionActivity}: android.view.InflateException: Binary XML file line #49: Error inflating class Button
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2702)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2767)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.app.ActivityThread.access$900(ActivityThread.java:177)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1449)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.os.Handler.dispatchMessage(Handler.java:102)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.os.Looper.loop(Looper.java:145)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.app.ActivityThread.main(ActivityThread.java:5951)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at java.lang.reflect.Method.invoke(Native Method)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at java.lang.reflect.Method.invoke(Method.java:372)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
12-17 10:56:53.950: E/AndroidRuntime(7251): Caused by: android.view.InflateException: Binary XML file line #49: Error inflating class Button
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:770)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:821)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at test.dci.android.view.fragment.TransactionFragment.onCreateView(TransactionFragment.java:71)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1036)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1226)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1328)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v4.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2284)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v4.app.FragmentController.onCreateView(FragmentController.java:111)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v4.app.FragmentActivity.dispatchFragmentsOnCreateView(FragmentActivity.java:314)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v4.app.BaseFragmentActivityHoneycomb.onCreateView(BaseFragmentActivityHoneycomb.java:31)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v4.app.FragmentActivity.onCreateView(FragmentActivity.java:79)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at test.dci.android.view.activity.TransactionActivity.onCreateView(TransactionActivity.java:1)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:740)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.view.LayoutInflater.rInflate(LayoutInflater.java:813)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.view.LayoutInflater.inflate(LayoutInflater.java:511)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.view.LayoutInflater.inflate(LayoutInflater.java:415)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.view.LayoutInflater.inflate(LayoutInflater.java:366)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v7.app.AppCompatDelegateImplV7.setContentView(AppCompatDelegateImplV7.java:256)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:109)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at test.dci.android.view.activity.TransactionActivity.onCreate(TransactionActivity.java:31)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.app.Activity.performCreate(Activity.java:6289)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1119)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2655)
12-17 10:56:53.950: E/AndroidRuntime(7251):     ... 10 more
12-17 10:56:53.950: E/AndroidRuntime(7251): Caused by: java.lang.RuntimeException: Failed to resolve attribute at index 12
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.content.res.TypedArray.getDimensionPixelSize(TypedArray.java:582)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.widget.TextView.<init>(TextView.java:1400)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.widget.Button.<init>(Button.java:115)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.widget.Button.<init>(Button.java:108)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:62)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v7.widget.AppCompatButton.<init>(AppCompatButton.java:58)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:98)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v7.app.AppCompatDelegateImplV7.createView(AppCompatDelegateImplV7.java:938)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at android.support.v7.app.AppCompatDelegateImplV7.onCreateView(AppCompatDelegateImplV7.java:992)
12-17 10:56:53.950: E/AndroidRuntime(7251):     at 

I am trying to follow the The MDC Codelab on codelabs.developers.google.com with the latest library versions.
The EditTextandroid.support.design.widget.TextInputEditText seems to work as expected however upon using the android.support.design.button.MaterialButton a runtime InflateException is thrown.

Gradle config:

compileSdkVersion 28

minSdkVersion 21

targetSdkVersion 28

dependencies {
   def lifecycle_version = "1.1.1"
   def nav_version = "1.0.0-alpha05"
   def work_version = "1.0.0-alpha06"
   def supportLibraryVersion = "28.0.0-rc01"

   implementation fileTree(include: ['*.jar'], dir: 'libs')
   api "android.arch.lifecycle:extensions:$lifecycle_version"
   api "android.arch.lifecycle:common-java8:$lifecycle_version"
   api "android.arch.navigation:navigation-fragment:$nav_version"
   api "android.arch.navigation:navigation-ui:$nav_version"
   api "android.arch.work:work-runtime:$work_version"

   api ("com.android.support:appcompat-v7:$supportLibraryVersion", {
       exclude group: 'com.android.support', module: 'support-media-compat'
   })
   api ("com.android.support:design:$supportLibraryVersion", {
       exclude group: 'com.android.support', module: 'support-media-compat'
   })
   api ("com.android.support:cardview-v7:$supportLibraryVersion", {
       exclude group: 'com.android.support', module: 'support-media-compat'
   })
   api ("com.android.support:customtabs:$supportLibraryVersion", {
       exclude group: 'com.android.support', module: 'support-media-compat'
   })

StackTrace

    E/XXXXXXApp: Unhandled Exception - Application Crash
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.XXXXXX/com.XXXXXX.activities.XXXXXXActivity}: android.view.InflateException: Binary XML file line #84: Binary XML file line #84: Error inflating class android.support.design.button.MaterialButton
    at com.XXXXXXActivity.onCreate(LoginActivity.java:107)
...

 Caused by: java.lang.IllegalArgumentException: This component requires that you specify a valid TextAppearance attribute. Update your app theme to inherit from Theme.MaterialComponents (or a descendant).
                 at android.support.design.internal.ThemeEnforcement.checkTextAppearance(ThemeEnforcement.java:170)
                 at android.support.design.internal.ThemeEnforcement.obtainStyledAttributes(ThemeEnforcement.java:75)
                 at android.support.design.button.MaterialButton.<init>(MaterialButton.java:140)
                 at android.support.design.button.MaterialButton.<init>(MaterialButton.java:133)

EDIT:
Added more details to stacktrace and figured out that the problem was to do with the fact that the App Theme needs to be inherited from Theme.MaterialComponents.

Понравилась статья? Поделить с друзьями:
  • 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