How to Select first chip as default progrmatically in Android Java?

603 views Asked by At

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?

3

There are 3 answers

0
Gabriele Mariotti On

You can use the the method: chipGroup.check(id). 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());
0
Abdul Basit On

you can simply use

 val firstChipId = chipGroup.getChildAt(0)?.id ?: View.NO_ID      
    chipGroup.check(firstChipId) 
0
Anh Huynh On

You can simply achieve this by this code in XML

  <com.google.android.material.chip.Chip
        android:checked="true"
        android:id="@+id/chip_song"
   />