InflateException при использовании TextInputLayout

Я пытаюсь использовать TextInputEditText из Material Design (https://github.com/material-components/material-components-android/blob/master/docs/components/TextInputLayout.md), и я получаю исключение во время выполнения.

Это часть журнала запуска:

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.grigori.materialtextedit, PID: 12036
              java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.grigori.materialtextedit/com.example.grigori.materialtextedit.MainActivity}: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class com.google.android.material.textfield.TextInputLayout
                  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)
                  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3048)
                  at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
                  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:1808)
                  at android.os.Handler.dispatchMessage(Handler.java:106)
                  at android.os.Looper.loop(Looper.java:193)
                  at android.app.ActivityThread.main(ActivityThread.java:6669)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
               Caused by: android.view.InflateException: Binary XML file line #9: Binary XML file line #9: Error inflating class com.google.android.material.textfield.TextInputLayout
               Caused by: android.view.InflateException: Binary XML file line #9: Error inflating class com.google.android.material.textfield.TextInputLayout
               Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.material.textfield.TextInputLayout" on path: DexPathList

Я вырезал этот журнал по DexPathList, который содержит много путей к файлам apk, например:

zip file "/data/app/com.example.grigori.materialtextedit-jamgTcrgG9neBKIMcqDo7Q==/base.apk"

Мой xml-файл:

<android.support.constraint.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">

<com.google.android.material.textfield.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <com.google.android.material.textfield.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/hint_text"/>

</com.google.android.material.textfield.TextInputLayout>

Мои зависимости build.gradle:

    dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-rc01'
implementation 'com.android.support.constraint:constraint-layout:1.1.2'
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'}     

comment
Та же проблема для меня, я также добавил реализацию в build.gradle. Он работает почти для всех устройств. На некоторых устройствах vivo происходит сбой каждый раз. Есть идеи, почему проблема касается только устройств vivo?   -  person Midhun Murali    schedule 05.08.2019


Ответы (25)


Столкнулся с этой проблемой при реализации AndroidX в моем существующем проекте.

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

XML макета

<com.google.android.material.textfield.TextInputLayout
    android:id="@+id/userNameWrapper"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/TextLabel">

Старый стиль

<style name="TextLabel" parent="TextAppearance.AppCompat">
        <item name="android:textColorHint">@color/hint_color</item>
        <item name="android:textSize">@dimen/text_20sp</item>
        <item name="colorControlNormal">@color/primaryGray</item>
        <item name="colorControlActivated">@color/colorPrimary</item>
    </style>

Новый стиль

<style name="TextLabel" parent="Widget.MaterialComponents.TextInputLayout.FilledBox">
        <item name="android:textColorHint">@color/hint_color</item>
        <item name="android:textSize">@dimen/text_20sp</item>
        <item name="colorControlNormal">@color/primaryGray</item>
        <item name="colorControlActivated">@color/colorPrimary</item>
    </style>
person Mihir Palkhiwala    schedule 07.12.2018
comment
я думаю, нет необходимости добавлять реализацию 'com.google.andr ....... если пользователь использует androidx - person giveJob; 25.04.2019
comment
поделитесь стилем для намека на цвет.? - person Atif AbbAsi; 19.04.2020

Обновите свои темы в папке @style, унаследовав одну из следующих тем:

Theme.MaterialComponents
Theme.MaterialComponents.NoActionBar
Theme.MaterialComponents.Light
Theme.MaterialComponents.Light.NoActionBar
Theme.MaterialComponents.Light.DarkActionBar

как это:

    <style name="AppTheme.NoActionBar"    parent="Theme.MaterialComponents.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimaryCustom</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDarkCustom</item>
    <item name="colorAccent">@color/colorAccentCustom</item>
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
person Md. Yamin Mollah    schedule 06.05.2019
comment
Моя особая проблема заключалась в том, что я пытался использовать стиль с родителем Theme.AppCompat.Light.NoActionBar, а некоторые виджеты были материальными. Кажется, они не очень хорошо играют вместе. (Я изучаю Android, и вот как мне удалось исправить мое вылетающее приложение). - person Ikon; 02.06.2020

Это может быть просто проблема темы. Если вашим родителем TextInputLayout является MaterialComponents (как описано ниже)

<style name="TextInputLayout" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox">
   ...
</style>

И если ваша тема Activity (или App) является производной от AppCompat, ваше приложение выйдет из строя, потому что темы MaterialComponents и AppCompat несовместимы. Например, AppTheme (для действия или приложения) НЕ МОЖЕТ быть следующим:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

Вам также нужно будет установить для AppTheme значение MaterialComponents, как показано ниже:

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
   <item name="colorPrimary">@color/colorPrimary</item>
   <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
   <item name="colorAccent">@color/colorAccent</item>
</style>

Надеюсь, это может сработать.

person Ram Iyer    schedule 31.01.2020

Спасибо за ваши ответы. Проблема была в том, что я использовал com.google.android.material.textfield.TextInputLayout. Если вы используете этот элемент управления, вы должны добавить в свои зависимости:

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

В моем случае я переписываю свой xml на android.support.design.widget.TextInputLayout:

    <android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textColorHint="@color/colorPrimary"
    app:errorEnabled="true">

    <android.support.design.widget.TextInputEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textColor="@color/colorPrimary"
        android:textColorHint="@color/colorPrimary"
        android:hint="Username" />

</android.support.design.widget.TextInputLayout>

Кроме того, я добавил в свои зависимости:

implementation 'com.android.support:design:27.1.1'

Это решило мою проблему.

person grasdy    schedule 23.08.2018

Я также столкнулся с той же ошибкой в ​​​​AndroidX. У меня есть решение, которое сработало для меня.

Вместо использования Theme.AppCompat используйте стиль Theme.MaterialComponents в качестве AppTheme или для действия.

стиль.xml

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

Используйте библиотеку материалов Google.

implementation 'com.google.android.material:material:1.2.0'

Почему возникает эта проблема?

Я заметил, что вы используете собственный стиль TextInputLayout: style="@style/TextInputLayout"

Это должно быть @style/Widget.MaterialComponents.TextInputLayout.OutlinedBox или подобное. Поэтому в качестве родительской темы для Activity требуется Theme.MaterialComponents.

person Shubham Gupta    schedule 21.07.2020
comment
Мне удалось избежать проблемы, просто используя MaterialComponents вместо AppCompat в стилях, избегая использования альфа-канала библиотеки материалов. - person Ariel; 01.08.2020

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

<style name="Theme.MyApp" parent="Theme.MaterialComponents.DayNight">
   <!-- ... -->
</style>
person Saad Lembarki    schedule 04.02.2020

На самом деле то, что большинство людей утверждают в отношении AppTheme, неверно!

Если вы используете androidx и НЕ хотите иметь тему приложения MaterialComponents

<!--style name="AppTheme" parent="Theme.MaterialComponents..."-->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">

Вы всегда можете сделать следующее и добавить тему MaterialComponents только в родительский контейнер:

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:theme="@style/Theme.MaterialComponents">

            <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/performing_attr1"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="Label"
                style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox">

                <com.google.android.material.textfield.TextInputEditText
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:inputType="number"/>
            </com.google.android.material.textfield.TextInputLayout>
person Tobi    schedule 02.11.2020

Добавьте эту зависимость в приложение Gradle

implementation 'com.google.android.material:material:1.1.0-alpha09'

Добавьте этот стиль в style.xml для вашего TextInputLayout.

<style name="TextLabel" parent="Widget.MaterialComponents.TextInputLayout.FilledBox">
    <item name="android:textColorHint">@color/colorGray600</item>
    <item name="android:textSize">@dimen/text_20sp</item>
    <item name="colorControlNormal">@color/colorGray900</item>
    <item name="colorControlActivated">@color/colorPrimary</item>
</style>

Добавьте это в свой TextInputLayout, как это

android:theme="@style/TextLabel"

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

Theme.MaterialComponents.Light

Теперь это решит проблему InflateException. но если у вас есть векторные рисунки, выполните следующие действия ниже

1. Вам необходимо включить поддержку векторов AndroidX в файле build.gradle вашего приложения:

android {
...
defaultConfig {
    ...
    vectorDrawables.useSupportLibrary = true
} }

2. Если вы хотите декларативно (т. е. в своих макетах) установить чертежи, тогда appcompat предлагает ряд атрибутов *Compat, которые следует использовать вместо стандартных атрибутов платформы:

ImageView, ImageButton:

Не делайте: android:src Делайте: app:srcCompat

CheckBox, RadioButton:

Не делайте: android:button Делайте: app:buttonCompat TextView (начиная с appcompat:1.1.0): Не делайте: android:drawableStart android:drawableTop и т. д. Делайте: app:drawableStartCompat app:drawableTopCompat и т. д.

Поскольку эти атрибуты являются частью библиотеки appcompat, обязательно используйте пространство имен app:. Внутри эти представления AppCompat* используют сами ресурсы AppCompatResources, чтобы разрешить загрузку векторов.

3. Если вы хотите использовать внутренний код,

val drawable = AppCompatResources.getDrawable(context, R.drawable.my_vector)

**4.**Если вы используете привязку данных, это можно сделать с помощью пользовательского адаптера привязки:

/* Copyright 2018 Google LLC.
SPDX-License-Identifier: Apache-2.0 */
@BindingAdapter("indeterminateDrawableCompat")
fun bindIndeterminateProgress(progressBar: ProgressBar, @DrawableRes id: Int) {
  val drawable = AppCompatResources.getDrawable(progressBar.context, id)
  progressBar.indeterminateDrawable = drawable
}

Надеюсь, это решит проблему.

person Jahangir Kabir    schedule 04.08.2019

вы должны изменить

файл build.gradle в

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.0.0-beta01'

    testImplementation 'junit:junit:4.12'

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

xml-файл в

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:focusable="false"
    android:clickable="true">


   <LinearLayout
       android:id="@+id/linear"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:orientation="vertical">

   <com.google.android.material.textfield.TextInputLayout
       style="@style/TextInputLayout"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="UserName"
       android:layout_margin="15dp">

      <com.google.android.material.textfield.TextInputEditText
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:inputType="text"
          android:maxLines="1" />
   </com.google.android.material.textfield.TextInputLayout>

   <com.google.android.material.textfield.TextInputLayout
       style="@style/TextInputLayout"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:hint="Email"
       android:layout_margin="15dp">

      <com.google.android.material.textfield.TextInputEditText
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:inputType="textEmailAddress"
          android:maxLines="1" />
   </com.google.android.material.textfield.TextInputLayout>

      <com.google.android.material.textfield.TextInputLayout
          style="@style/TextInputLayout"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:hint="Password"
          android:layout_margin="15dp">

         <com.google.android.material.textfield.TextInputEditText
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:inputType="textPassword"
             android:maxLines="1" />
      </com.google.android.material.textfield.TextInputLayout>



   </LinearLayout>

</RelativeLayout>

MainActivity.java

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
}
person deep gothi    schedule 29.11.2018

Если вы используете com.android.support:design:28.0.0 или новее, классы android.support.design.widget.TextInputLayout и android.support.design.widget.TextInputEditText больше не существуют в библиотеке.

Если вы используете уровень API 28 (или новее), вы должны использовать библиотеку com.google.android.material:material, как описано в других ответах здесь.

person Moshe Katz    schedule 12.06.2019

Если вы столкнулись с этой ошибкой во время инструментального теста, вам может потребоваться определить свой стиль с помощью. val scenario = launchFragmentInContainer<LoginFragment>(themeResId = R.style.MyTheme)

person Will Hughes    schedule 17.07.2020

Основная причина этой фатальной ошибки заключается в том, что при стилизации макета ввода текста очень важно также изменить тему приложения или не приложения, а затем создать другой стиль для конкретного экрана. Это можно сделать с помощью

Перейдите к значениям, затем откройте файл styles.xml.

обычно это тема вашего приложения

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

тут главное поменять

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">

изменить appcompat на материальные компоненты

Если вы не хотите менять тему приложения

<style name="MaterialAppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">

Я думаю, что это будет работать нормально и поможет вам раздуть контурную рамку или любую конкретную тему в поле ввода.

person Hemant Kumar Rathore    schedule 16.04.2021

Эта ошибка возникает, когда
"app:passwordToggleEnabled="true" or app:passwordToggleTint="#fff" находится в com.google.android.material.textfield.TextInputLayout.

При удалении работает.

Его можно установить программно:

TextInputLayout input_password_layout=(TextInputLayout)findViewById(R.id.input_password_layout);
    input_password_layout.setPasswordVisibilityToggleEnabled(true);
    input_password_layout.setPasswordVisibilityToggleDrawable(R.drawable.back);
person Beulah Ana    schedule 02.12.2018

была такая же ситуация. причина была в "зоопарке" в моих зависимостях ))

17.07.2019 - правильный список:

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
implementation 'androidx.appcompat:appcompat:1.0.2'
implementation 'androidx.core:core-ktx:1.0.2'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.google.android.material:material:1.0.0'
person Tswet    schedule 17.07.2019

Я получил ту же ошибку, потому что изменил зависимости в Gradle Build на

implementation 'com.google.android.material:material:1.2.1'

затем я возвращаю его обратно к

> implementation 'com.google.android.material:material:1.0.0'

и ошибка исчезает.

person Atul Yadav    schedule 07.09.2020

Просто зайдите в приложение › res › values ​​› styles.xml и измените тему на: Theme.MaterialComponents.Light.DarkActionBar. Это будет выглядеть так:

<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>
person UTTAM    schedule 18.10.2020

если вы используете обычный стиль в проекте и используете материальный компонент, используйте обновленный стиль

   // Old Style
  <style name="AppTheme.NoActionBar" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="android:fontFamily">@font/roboto_regular</item>
</style>

  // Updated Style

 <style name="AppTheme.NoActionBar" parent="Theme.MaterialComponents.Light.NoActionBar.Bridge">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <item name="android:fontFamily">@font/roboto_regular</item>
</style>

Всего лишь небольшое изменение, и вы получите результат...

person Sarthak Dhami    schedule 21.10.2020

В ваших зависимостях добавьте:

implementation 'com.android.support:design:27.0.0'

Надеюсь, это поможет вам .. попробуйте ..

person Ümañg ßürmån    schedule 21.08.2018
comment
Я пытался добавить implementation 'com.android.support:design:28.0.0-rc01', но это не помогло - person grasdy; 22.08.2018
comment
Вы пробовали приведенную выше реализацию? - person Ümañg ßürmån; 22.08.2018

вы должны добавить

 implementation 'com.github.material-components:material-components-android:1.0.0-rc01'

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

  dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0-rc01'
    implementation 'com.android.support.constraint:constraint-layout:1.1.2'
    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'
    implementation 'com.github.material-components:material-components-android:1.0.0-rc01'
    }  
person Badran    schedule 21.08.2018

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

И хотя предварительный просмотр в Android Studio отображал компонент материала как обычный EditText и показывал несколько предупреждений, на реальном устройстве он отображался правильно.

Поэтому, чтобы сэкономить время людям, ищущим эту ошибку (для меня это был потерянный час), просто попробуйте это на устройстве!

person Rainmaker    schedule 25.09.2018

Эта ошибка произошла со мной, когда в зависимостях уровня моего приложения я использовал дизайн материалов версии 1.2.0-alpha06, это новая версия. Пришлось вернуть на версию 1.0.0-beta01 и все заработало.

person Junior Joseph    schedule 25.05.2020

Попробуй это

    <style name="FloatingTextStyle" parent="Widget.Design.TextInputLayout">
        <!-- Hint color and label color in FALSE state -->
        <item name="android:textColorHint">@android:color/darker_gray</item>
        <item name="android:textSize">20sp</item>
        <!-- Label color in TRUE state and bar color FALSE and TRUE State -->
        <item name="colorAccent">@color/colorPrimaryDark</item>
        <item name="colorControlNormal">@color/colorPrimaryDark</item>
        <item name="colorControlActivated">@color/colorPrimaryDark</item>
    </style>
person Chethana Arunodh    schedule 19.10.2020

Не забудьте также изменить в файле манифеста все действия со стилем на Theme.MaterialComponents.

person Miguel Silva    schedule 11.12.2020

Эта проблема только из-за выбора темы.

Мы можем использовать Theme.MaterialComponents.DayNight.DarkActionBar в файле XML

Например: android:theme="@style/Theme.MaterialComponents.DayNight.DarkActionBar"

person Chaman Panchal    schedule 23.02.2021

Измените стиль вашего приложения в файле styles.xml на это:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar.Bridge">
    <!-- Customize your theme here. -->

</style>

Это сработало для меня

person Mixdor    schedule 07.04.2021