Search code examples
javaandroidarraylistandroid-chips

How to display all the elements of ArrayList as Chips in Android


I have an ArrayList<String> like this [Angularjs, JavaScript, Css]

In my Adapter where I get the ArrayList of tags from another Intent. I tried to display all the elements of the ArrayList as Chips with the below approach, but I get only the last element of the ArrayList. I only see one Chip with the last element of the ArrayList.

for (String tag: card.getTags()) {
  Log.d(TAG, "tag - " + tag);
  holder.tags.setText(tag);
}

Could anyone please guide, how do I change my code to display all the elements of the ArrayList as Chips.


Solution

  • If you are talking about Chips.

    Add a ChipGroup in xml layout where you want to show your chips

    <com.google.android.material.chip.ChipGroup
     android:id="@+id/chipGroup"
     android:layout_width="match_parent"
     app:chipSpacingVertical="2dp"
     android:layout_height="wrap_content"/>
    

    Now you can use this method to add your ArrayList as Chip in ChipGroup :

    private void addChip(String pItem, ChipGroup pChipGroup) {
        Chip lChip = new Chip(this);
        lChip.setText(pItem);
        lChip.setTextColor(getResources().getColor(R.color.primary_text));
        lChip.setChipBackgroundColor(getResources().getColorStateList(R.color.chip_bg));
    
        pChipGroup.addView(lChip, pChipGroup.getChildCount() - 1);
      }