How to create a Tag-list in android

July 23, 2020

Image from instagram

Requirements:

  • Number of tags are not fixed
  • Tags need to wrap to next line if there’e no room
  • No horizontal scroll
  • Variable height, depending on the number of tags

How to do it?

Flexbox for Android!

From the docs:

FlexboxLayout is a library project which brings the similar capabilities of CSS Flexible Box Layout Module to Android.

Maintained by Google itself, Flexbox Layout can give you all the CSS flexbox properties for your native UI elements.

Using Flexbox layout to create a tag list:

  • Install Flexbox layout in your app In your app’s build.gradle file, add:
dependencies {
    implementation 'com.google.android:flexbox:2.0.1'
}
  • Add flexbox layout in your layout xml file:
<com.google.android.flexbox.FlexboxLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="horizontal"
    android:layout_height="wrap_content"
    tools:context=".MainActivity">

      ...

    </com.google.android.flexbox.FlexboxLayout>
  • Add your TextViews/Buttons inside this layout. I’ve added 9 text views and my layout looks something like this:
  • Add the flexWrap property to your flexbox
    app:flexWrap="wrap"

And now your layout will look something like this:

  • And since your tag list is not fixed and you might be fetching them from your backend, you’ll need to programatically add the Tags to your Flexbox layout.

Written by Gagandeep Rangi who likes to talk about himself in third person. Twitter Instagram

Email icon