InvocationTargetException и «Не удалось разрешить атрибут в индексе 13» при обновлении до com.google.android.material: material: 1.1.0-alphaXX - PullRequest
0 голосов
/ 23 мая 2019

Сводка проблемы

В своем приложении для одного действия я использую пользовательский фрагмент NavigationDrawerFragment с androidx.drawerlayout.widget.DrawerLayout , содержащий com.google.android.material.navigation.NavigationView как боковое меню для навигации между фрагментами.

Недавно я перешел с библиотеки поддержки v7 на AndroidX и сегодня пытался обновить с com.google.android.material: материал: 1.0.0 до com.google.android.material: материал: 1.1.0-alpha06 , но мое приложение вылетает при запуске:

  android.view.InflateException: Binary XML file line #37: 
Error inflating class com.google.android.material.navigation.NavigationView
  Caused by: java.lang.reflect.InvocationTargetException
  Caused by: java.lang.RuntimeException: Failed to resolve attribute at index 13

Расследование

Понижение до Материал: 1.1.0-alpha05 , -alpha04 , -alpha03 , -alpha02 и -alpha01 выдает другие, но похожие сообщения об ошибкахвнутри фрагмента по умолчанию, загруженного в DrawerLayout:

  android.view.InflateException: Binary XML file line #2: 
Error inflating class androidx.cardview.widget.CardView
  Caused by: java.lang.reflect.InvocationTargetException
   Caused by: java.lang.RuntimeException: Failed to resolve attribute at index 2

Понижение до Материал: 1.0.0 не дает ошибок на моем физическом тестирующем устройстве Android 5.1.1 Samsung Galaxy J3

Поиск похожих случаев

Наиболее важные вопросы по StackOverflow не имеют принятых ответов:

  1. Не удалось разрешить атрибутс индексом 13 в android.content.res.TypedArray.getDrawable ()
  2. ANDROID: не удалось разрешить атрибутRibute с индексом 13

Другие производят другие сообщения об ошибках (вызвано ...) , как NullPointerException, другой индекс атрибута число или упоминание v7 android поддержка библиотеки , которую я не использую, т.е. (сокращенный список):

Android XML: RuntimeException: не удалось разрешить атрибут в индексе 6 CoordinatorLayout - не удалось разрешить атрибут в индексе 1 в android.content.res.TypedArray.getDrawable

И никто из них не упоминает новую библиотеку material .

Что является общим - все эти ошибки связаны с внутренними атрибутами android Theme, такими как?attr или предопределенные цвета и значения в style.xml

Мой код

NavigationDrawerFragment.java

public class NavigationDrawerFragment extends Fragment
{
  private DrawerLayout    drawerLayout;
  private Toolbar         toolbar;
  private NavigationView  navigationView;
  private View            toolbarView;

  @Nullable @Override
  public final View
  onCreateView
  (@Nullable final LayoutInflater inflater,
   @Nullable final ViewGroup container,
   @Nullable final Bundle savedInstanceState)
  {
    View result = null;
    getActivity().setTheme
    (R.style.AppTheme_NavigationDrawerStyle);

    if((inflater != null) && (container != null))
    {
      final View view = inflater.inflate
      (R.layout.navigation_drawer_fragment, container, false);

      if(view != null)
      {
        toolbar = view.findViewById(R.id.toolbar);
        drawerLayout = view.findViewById(R.id.drawerLayout);
        navigationView = view.findViewById(R.id.navigationView);

        if(toolbar != null)
        {
          toolbarView = 
          getLayoutInflater().inflate
          (R.layout.toolbar_view_layout, toolbar);

          if(toolbarView != null)
          {
            final String title = getString(R.string.app_name);
            toolbar.setTitle(title);

            ((AppCompatActivity) getActivity())
            .setSupportActionBar(toolbar);

            ((AppCompatActivity) getActivity())
            .getSupportActionBar().setTitle(title);
          }
        }
      }
      result = view;
    }
    return result;
  }
}

navigation_drawer_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.drawerlayout.widget.DrawerLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:id="@+id/drawerLayout"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:fitsSystemWindows="true"
  tools:openDrawer="start"
  tools:context=".view.activity.MainActivity">

  <androidx.appcompat.widget.LinearLayoutCompat
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include
      layout="@layout/toolbar"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"/>

    <!-- Layout contents of main body (drawer will slide over this) -->
    <FrameLayout
      android:id="@+id/contentFrame"
      android:layout_width="match_parent"
      android:layout_height="match_parent"
      android:isScrollContainer="true">
    </FrameLayout>

  </androidx.appcompat.widget.LinearLayoutCompat>

  <!-- Container for contents of drawer (header and items) -->
  <com.google.android.material.navigation.NavigationView
    android:id="@+id/navigationView"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    android:theme="@style/AppTheme.NavigationDrawerStyle"
    app:headerLayout="@layout/menu_layout_navigation_drawer_header"
    app:menu="@menu/menu_navigation_view_items"/>

</androidx.drawerlayout.widget.DrawerLayout>

styles.xml

<resources> 

  <!-- Base application theme-->
  <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="colorControlActivated">@color/colorAccent</item>
    <item name="colorControlHighlight">@color/colorAccent</item>
    <item name="android:textColorHighlight">@color/colorAccent</item>
    <item name="cardViewStyle">@style/AppTheme.CardViewStyle</item>
    <item name="editTextStyle">@style/AppTheme.EditTextStyle</item>
    <item name="navigationViewStyle">
     @style/Widget.AppCompat.NavigationView
    </item>
  </style>
  <!-- / Base application theme-->

  <!-- CardView -->
  <style name="AppTheme.CardViewStyle" parent="Widget.AppCompat.CardView">
    <item name="cardPreventCornerOverlap">true</item>
    <item name="cardUseCompatPadding">true</item>
  </style>
  <!-- / CardView -->

  <!-- Navigation Drawer -->
  <style name="AppTheme.NavigationDrawerStyle" parent="ThemeOverlay.AppCompat.Light">
    <item name="android:textSize">@dimen/navigation_drawer_menu_fontsize</item>
    <item name="android:listPreferredItemHeightSmall">
     @dimen/navigation_drawer_menu_item_height_medium
    </item>
    <item name="listPreferredItemHeightSmall">
     @dimen/navigation_drawer_menu_item_height_medium
    </item>
    <item name="listPreferredItemPaddingLeft">
     @dimen/navigation_drawer_menu_item_padding_left
    </item>
    <item name="fontFamily">@string/roboto_medium</item>
  </style>
  <!-- / Navigation Drawer -->

</resources>

build.gradle (Модуль: приложение)

apply plugin: 'com.android.application'

android
{
  compileSdkVersion 28

  defaultConfig
  {
    applicationId = "net.cargo"

    minSdkVersion 14
    targetSdkVersion 28
    versionCode = 3
    versionName = "1.0.2"
    testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
    vectorDrawables {
      useSupportLibrary = true
    }
    multiDexEnabled = true
  }

  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
  }

  flavorDimensions "product", "mock"
  productFlavors {
  }

  buildToolsVersion '29.0.0 rc2'

  // different resource directories
  sourceSets {
    main {
      res.srcDirs = ['src/main/res']
    }
  }

  buildTypes {
    debug {
      ext.enableCrashlytics = true
      shrinkResources false
      minifyEnabled false
      zipAlignEnabled true
    }
  }
}

repositories {
  mavenCentral()
}

configurations {
  cleanedAnnotations
}

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

  // support material design
  implementation 'com.google.android.material:material:1.1.0-alpha06'

  // androidx support library
  implementation 'androidx.legacy:legacy-support-v4:1.0.0'
  implementation 'androidx.appcompat:appcompat:1.1.0-alpha05'
  implementation 'androidx.recyclerview:recyclerview:1.1.0-alpha05'
  implementation 'androidx.cardview:cardview:1.0.0'
  implementation 'androidx.vectordrawable:vectordrawable:1.1.0-beta01'
  implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta1'
  implementation 'androidx.multidex:multidex:2.0.1'

  // google architecture components
  implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0-alpha01'
  implementation 'androidx.lifecycle:lifecycle-common-java8:2.2.0-alpha01'
  implementation 'androidx.lifecycle:lifecycle-reactivestreams:2.2.0-alpha01'
  implementation 'androidx.room:room-runtime:2.1.0-beta01'
  implementation 'androidx.room:room-rxjava2:2.1.0-beta01'

  // annotation processors
  annotationProcessor 'androidx.lifecycle:lifecycle-compiler:2.2.0-alpha01'
  annotationProcessor 'androidx.room:room-compiler:2.1.0-beta01'

Нужна помощь

Я ожидал, что после обновления мое приложение будет успешно собрано, но что-то сломалосьв теме.

Интересно, есть ли способ исправить эту проблему.

1 Ответ

0 голосов
/ 23 мая 2019

Я нашел одну возможность для создания приложения, отредактировав мой файл styles.xml, заменив каждую запись Theme.AppCompat... на какую-то запись Theme.MaterialComponents..., хотя это не очень элегантно (и нарушает некоторые стили приложения):

  • <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    заменено на <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">

  • <style name="AppTheme.CardViewStyle" parent="Widget.AppCompat.CardView">
    заменено на <style name="AppTheme.CardViewStyle" parent="Widget.MaterialComponents.CardView">

  • <style name="AppTheme.NavigationDrawerStyle" parent="ThemeOverlay.AppCompat.Light">
    заменено на <style name="AppTheme.NavigationDrawerStyle" parent="ThemeOverlay.MaterialComponents.Light">

Я также заменил некоторые другие записи стиля, хотя некоторые из них не имеют точно соответствующего стиля:

  • <style name="RoundedButtonStyle" parent="Widget.AppCompat.Button.Colored">
    заменено на <style name="RoundedButtonStyle" parent="Widget.MaterialComponents.Button.OutlinedButton">

  • <style name="AboutApplicationDialog" parent="@style/Theme.AppCompat.Light.Dialog">
    заменено на <style name="AboutApplicationDialog" parent="@style/Theme.MaterialComponents.Light.Dialog">

  • <style name="AppTheme.EditTextStyle" parent="Widget.AppCompat.EditText">
    заменено на <style name="AppTheme.EditTextStyle" parent="Widget.MaterialComponents.TextInputLayout.OutlinedBox">

Если вы найдете другой способ, пожалуйста, ответьте)

...