在我的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)
它有效并应用样式。但是我在问自己,这是否真的是最简单的方法。你知道更好的吗?