此组件要求您指定有效的 TextAppearance 属性

This component requires that you specify a valid TextAppearance attribute

我的应用程序主题继承自 AppCompat,但我想动态使用 Chip,但是当我动态添加 Chips 时,应用程序崩溃并出现异常

This component requires that you specify a valid TextAppearance attribute. Update your app theme to inherit from Theme.MaterialComponents (or a descendant).

但是当我将应用程序主题扩展到 Material 时应用程序不会崩溃并且过滤芯片工作正常但我的问题是我不想从 Material 扩展主题因为它影响我的应用程序 UI, 这种情况下芯片怎么用?

编辑: 使用桥接器,它可以避免崩溃,但是当我点击芯片时,它不会改变我被点击的芯片的外观

Chip chip = new Chip(getContext());
        ChipDrawable chipDrawable = ChipDrawable.createFromAttributes(getContext(), null, 0, R.style.Widget_MaterialComponents_Chip_Filter);
        chip.setChipDrawable(chipDrawable);
        chip.setCheckable(true);
        chip.setText(itemArrayList.get(i).getName());
        binding.rvReport.addView(chip);

谢谢

您可以仅为继承自 Theme.MaterialComponents 的特定 Chip 指定一个主题,而不必修改您的应用程序范围的 AppCompat 主题:

<com.google.android.material.chip.Chip
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/Theme.MaterialComponents"/>

您可以查看 official documentation:

Your app theme should inherit from a Material Components theme.
If you can't change your theme, you can do one of the following:

  • Inherit from one of our Material Components Bridge themes
  • Continue to inherit from an AppCompat theme and add some new theme attributes to your theme.

对于芯片你也可以定义布局如下:

<com.google.android.material.chip.Chip
    xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/Widget.MaterialComponents.Chip.Filter"
    .../>

然后使用此代码:

Chip chip =
      (Chip) getLayoutInflater().inflate(R.layout.single_chip_layout, chipGroup, false);
//...
chipGroup.addView(chip);