1

在我的 xml 布局中,我有一个带有过滤芯片的芯片组。

<android.support.design.chip.ChipGroup
    android:id="@+id/chipGroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.chip.Chip
        style="@style/myStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    .....

</android.support.design.chip.ChipGroup>

由于有很多过滤器,在代码中添加它们似乎是合理的。问题是我需要style对每个芯片应用属性。

我试过了:

val chip = Chip(ContextThemeWrapper(context, R.style.myStyle))
binding.chipGroup.addView(chip)

没有效果

val chip = Chip(context, null, R.style.myStyle)
binding.chipGroup.addView(chip)

没有效果

我创建layout/filter_chip.xml并放了一个芯片模板

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.chip.Chip 
    xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/myStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

我用这样的代码创建它

val chip = inflater.inflate(R.layout.filter_chip, binding.chipGroup, false) as Chip   
binding.chipGroup.addView(chip)

它有效并且应用了样式。但我问自己这是否真的是实现它的最简单方法。你知道更好的吗?

4

1 回答 1

-1

我认为您可以通过使用所需样式创建 ContextThemeWrapper 来使用ContextThemeWrapper,然后将主题上下文传递给芯片的构造函数。

于 2019-03-26T23:45:41.790 回答