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'}     

У меня такая же проблема, я добавил реализацию в build.gradle. Работает практически на всех устройствах. На некоторых устройствах vivo каждый раз вылетает сбой. Есть идеи, почему проблема только в устройствах vivo?

Midhun Murali 05.08.2019 07:26
45
1
58 534
25

Ответы 25

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

 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'
    }  

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

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

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

Я пытался добавить implementation 'com.android.support:design:28.0.0-rc01', но это не помогло

grasdy 22.08.2018 07:37

вы пробовали реализацию, описанную выше?

Ümañg ßürmån 22.08.2018 08:06

Спасибо за ответы. Проблема была в том, что я использовал 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'

Это устранило мою проблему.

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

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

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

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

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);
    }
}

Эта ошибка возникает, когда
"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);

Столкнулся с этой проблемой при реализации 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>

Я думаю, что нет необходимости добавлять реализацию com.google.andr ....... если пользователь использует androidx

giveJob 25.04.2019 15:47

поделитесь стилем для цвета подсказки.?

Atif AbbAsi 19.04.2020 09:07

Обновите свои темы в папке @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>

Моя конкретная проблема заключалась в том, что я пытался использовать стиль с родительским элементом «Theme.AppCompat.Light.NoActionBar», а некоторые из виджетов были материальными. Кажется, они не очень хорошо играют вместе. (Я изучаю Android, и вот как мне удалось исправить сбой приложения).

Ikon 02.06.2020 17:38

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

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

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

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'

Добавьте эту зависимость в приложение 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:buttonCompatTextView (начиная с 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
}

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

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

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

И если ваша тема Activity (или приложения) является производной от 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>

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

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

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

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

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

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

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

style.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 в качестве родительской темы.

Мне удалось избежать проблемы, просто используя MaterialComponents вместо AppCompat в стилях, избегая использования альфа-канала библиотеки материалов.

Ariel 31.07.2020 23:27

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

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

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

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

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

Просто зайдите в приложение> res> значения> 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>

Попробуй это

    <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>

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

   // 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>

Небольшая мелочь, и вы получите результат ...

На самом деле, то, что большинство людей утверждает относительно 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>

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

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

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

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

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

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

</style>

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

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

Перейти к ценностям затем откройте 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">

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

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