如何在代码中为芯片应用“样式”?

时间:2019-03-23 21:25:32

标签: android android-chips

在我的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)

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

1 个答案:

答案 0 :(得分:0)

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