Get Chip Text on click chip

3.7k views Asked by At

I am new to android and trying to play with chips. I have chip group like this in xml

<com.google.android.material.chip.ChipGroup
                                android:padding="10dp"
                                android:id="@+id/tags"
                                android:layout_width="match_parent"
                                android:layout_height="wrap_content"
                                app:chipSpacing="10dp">

                            </com.google.android.material.chip.ChipGroup>

I am dynamically adding chip like this in it.

Chip chip = new Chip(getLayoutInflater().getContext());
            for(String genre : tags_text) {
               chip.setText(genre);
               tags.addView(chip);
           }

Adding chip is working fine. Now I want get chip text of clicked chip. I am trying to get it like this

chip.setOnClickListener(new View.OnClickListener() {

                                        public void onClick(View v) {
                                            int chipsCount = tags.getChildCount();
                                            String TagText ="";
                                            int i = 0;
                                            while (i < chipsCount) {
                                                Chip chip = (Chip) tags.getChildAt(i);
                                                if (chip.isChecked() ) {
                                                    TagText = chip.getText().toString();
                                                }
                                                i++;
                                            };
                                            Log.e("CHIPS", TagText+"-OK");
                                        }
                                    });

But I am getting empty text always. let me know if someone can help me for solve it. Thanks!

1

There are 1 answers

0
Gabriele Mariotti On BEST ANSWER

You can use:

    chip.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            String text = ((Chip) view).getText().toString();
            //...
        }
    });