如何使ChipGroup
像radioButton
一样工作,可以在更改背景颜色的同时一次选择一项。
我看到this link像这样的东西,但对我没有帮助,因为正在使用layoutInflater
来显示我的筹码项目。
firebaseFirestore.collection("Categories").addSnapshotListener((queryDocumentSnapshots, e) -> {
for (DocumentChange doc: queryDocumentSnapshots.getDocumentChanges()){
if (doc.getType() == DocumentChange.Type.ADDED){
Categories categories = doc.getDocument().toObject(Categories.class);
post_list.add(categories);
Chip chip = (Chip) getLayoutInflater().inflate(R.layout.chip_item_layout, chipGroup, false);
chip.setText(categories.getTitle());
chipGroup.addView(chip);
chipGroup.setOnCheckedChangeListener((chipGroup, id) -> {
Chip chip2 = ((Chip) chipGroup.getChildAt(chipGroup.getCheckedChipId()));
if (chip2 != null) {
for (int i = 0; i < chipGroup.getChildCount(); ++i) {
chipGroup.getChildAt(i).setClickable(true);
chip2.setChipBackgroundColorResource(R.color.customOrange);
}
chip2.setClickable(false);
}
});
}
}
});
答案 0 :(得分:1)
在您的ChipGroup
中使用app:singleSelection="true"
属性。这样,ChipGroup
可以配置为仅允许一次检查单个芯片。
<com.google.android.material.chip.ChipGroup
app:singleSelection="true"
..>
然后,您可以使用布局app:chipBackgroundColor
中的 chip_item_layout.xml
属性设置选择器颜色。
类似的东西:
<com.google.android.material.chip.Chip
style="@style/Widget.MaterialComponents.Chip.Choice"
app:chipBackgroundColor="@color/chip_background_color"
..>
请注意style="@style/Widget.MaterialComponents.Chip.Choice"
,因为它将芯片定义为android:checkable="true".
chip_background_color
是一个选择器,您可以在其中定义不同状态下喜欢的颜色。它是默认选择器,您可以更改它:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- 24% opacity -->
<item android:alpha="0.24" android:color="?attr/colorPrimary" android:state_enabled="true" android:state_selected="true"/>
<item android:alpha="0.24" android:color="?attr/colorPrimary" android:state_enabled="true" android:state_checked="true"/>
<!-- 12% of 87% opacity -->
<item android:alpha="0.10" android:color="?attr/colorOnSurface" android:state_enabled="true"/>
<item android:alpha="0.12" android:color="?attr/colorOnSurface"/>
</selector>
所选颜色由您的情况下第一行(android:state_selected="true"
的颜色定义。
如果您希望通过编程方式进行操作,只需使用setChipBackgroundColorResource
方法(在OnCheckedChangeListener
中为不)。
chip.setChipBackgroundColorResource(R.color.chip_background_color);
如果您要至少需要一项选择,则可以使用 app:selectionRequired
属性。此属性需要1.2.0(从1.2.0-alpha02
开始)