英文:
How to Select first chip as default progrmatically in Android Java?
问题
chip_group_filter.removeAllViews();
for (FilterModel filterModel : Common.categorySelected.getFilters()) {
Chip chip = (Chip) getLayoutInflater().inflate(R.layout.layout_filter_item, null);
chip.setText(new StringBuilder(filterModel.getName()));
chip.setCheckedIconVisible(false);
chip_group_filter.addView(chip);
chip.setChipBackgroundColorResource(R.color.lightGray);
chip.setTextColor(getResources().getColor(android.R.color.black));
chip.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
seeSelectedChip(chip);
serviceListViewModel.loadServicesByFilter(chip.getText().toString());
}
}
});
}
我想将第一个芯片选为默认芯片,并希望执行相应的 checkChangedListener
事件。如何编写这个逻辑?
<details>
<summary>英文:</summary>
I have defined my chipgroup in my XML and adding chips programtically as below:
chip_group_filter.removeAllViews();
for(FilterModel filterModel : Common.categorySelected.getFilters()){
Chip chip = (Chip) getLayoutInflater().inflate(R.layout.layout_filter_item, null);
chip.setText(new StringBuilder(filterModel.getName()));
chip.setCheckedIconVisible(false);
chip_group_filter.addView(chip);
chip.setChipBackgroundColorResource(R.color.lightGray);
chip.setTextColor(getResources().getColor(android.R.color.black));
chip.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
seeSelectedChip(chip);
serviceListViewModel.loadServicesByFilter(chip.getText().toString());
}
}
});
I want to select first chip as default chip and want to execute checkChangedListener event for the same. How to write that logic?
</details>
# 答案1
**得分**: 2
你可以使用方法:[`chipGroup.check(id)`][1]。它使用芯片的`id`进行选择。
你可以使用:
chipGroup.check(chip.getId());
或者如果你没有id:
chipGroup.check(chipGroup.getChildAt(0).getId());
[1]: https://developer.android.com/reference/com/google/android/material/chip/ChipGroup#check
<details>
<summary>英文:</summary>
You can use the the method: [`chipGroup.check(id)`][1]. It works with the `id` of the chip to select.
You can use:
chipGroup.check(chip.getId());
or if you don't have the id
chipGroup.check(chipGroup.getChildAt(0).getId());
[1]: https://developer.android.com/reference/com/google/android/material/chip/ChipGroup#check
</details>
# 答案2
**得分**: 0
你可以简单地使用:
```kotlin
val firstChipId = chipGroup.getChildAt(0)?.id ?: View.NO_ID
chipGroup.check(firstChipId)
英文:
you can simply use
val firstChipId = chipGroup.getChildAt(0)?.id ?: View.NO_ID
chipGroup.check(firstChipId)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论