试试这个逻辑:
您的活动:
int i=0;
String chipArr[]={"First","Second","Third","Fourth"};
int selectedChipId=0;
for (final String chipName : chipArr) {
Chip chip = (Chip) layoutInflater.inflate(R.layout.cat_chip_group_item_filter, chipGroup, false);
chip.setText(chipName);
chip.setId(i);
}
for (final String chipName : fileNameChip) {
LayoutInflater layoutInflater = getLayoutInflater();
Chip chip = (Chip) layoutInflater.inflate(R.layout.cat_chip_group_item_filter, chipGroup, false);
chip.setText(chipName);
chip.setId(i);
if (i == 0) chip.setSelected(true);
chip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
selectedChipId=v.getId();
}
});
chipGroup.addView(chip);
i++;
}
chipGroup.setOnCheckedChangeListener(new ChipGroup.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(ChipGroup group, int checkedId) {
Log.d(TAG, "onCheckedChanged: " + checkedId);
if (checkedId == selectedChipId) {
chip.setSelected(true);
}
}
});
活动布局:
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".activity.ShowCodeActivity">
<HorizontalScrollView
android:id="@+id/horScrollView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:scrollbars="none">
<com.google.android.material.chip.ChipGroup
android:id="@+id/chip_group_code_files"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="@dimen/margin_4dp"
android:layout_marginEnd="@dimen/margin_4dp"
app:singleLine="true"
app:singleSelection="true" />
</HorizontalScrollView>
</RelativeLayout>
您的cat_chip_group_item_filter .xml:
<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.chip.Chip
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
style="@style/Widget.MaterialComponents.Chip.Filter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
让我知道它是否对你有用,因为我没有测试过!!