Search code examples
androidtagsmaterial-componentsmaterial-components-androidandroid-chips

How do I create this type of xml layout


enter image description herePlease I need help on achieving this type of layout in android xml.

I have tried with RecyclerView and this library but I still did not get what I wanted.

Any ideas?

Thanks


Solution

  • Just use the Material Components Library and the Chip component.

    You can define it with a layout if it is static:

    <com.google.android.material.chip.ChipGroup
        android:id="@+id/chip_group"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
    
        <!-- Chips can be declared here, or added dynamically. -->
    
        <com.google.android.material.chip.Chip
            style="@style/Widget.MaterialComponents.Chip.Entry"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:chipIcon="@drawable/...."
            android:text="@string/..."/>
    
         .....
    
    </com.google.android.material.chip.ChipGroup>
    

    Or you can do it programmatically.
    Define the layout for the single Chip (chip_layout.xml)

    <com.google.android.material.chip.Chip
        xmlns:android="http://schemas.android.com/apk/res/android"
        style="@style/Widget.MaterialComponents.Chip.Choice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    

    In your code:

    ChipGroup reflowGroup = view.findViewById(R.id.chip_group);
    for (.....) {
          Chip chip =
              (Chip) getLayoutInflater().inflate(R.layout.chip_layout, chipGroup, false);
          chip.setText(....);
          .....
          chipGroup.addView(chip);
        }
    

    enter image description here