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