Search code examples
javaandroidtextview

Display string as a multiple tag in a single TextView


The first thing, I know how to split the string and my question is not about splitting it at comma or space.

I have a string like this:

"hello,nice,owesome"

and I want to display it like this:

enter image description here

This is how I separate my string:

ArrayList<String> list = Arrays.asList(str.split(","));

now I have separated greeting list, but I don't know how to display this list as multiple tags in a single TextView.


Solution

  • create your chip layout like this

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/background_chip"
        android:gravity="center"
        android:paddingLeft="4dp"
        android:paddingRight="4dp">
    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/background_chip"
        android:gravity="center"
        android:paddingBottom="6dp"
        android:paddingLeft="8dp"
        android:paddingRight="8dp"
        android:paddingTop="6dp">
    
        <TextView
            android:id="@+id/chip_text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:paddingLeft="6dp"
            android:text="#SoftwereEngineer"
            android:textColor="@android:color/white"
            android:textSize="14sp" />
    
    </LinearLayout>
    </LinearLayout>
    

    Then create a container where you want to add these chips

     <LinearLayout
        android:id="@+id/chip_container"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/background_chip"
        android:gravity="center"
        android:orientation="horizontal"
        android:paddingBottom="4dp"
        android:paddingTop="4dp"/>
    

    in you java file add the chips to this container

    LinearLayout linearLayout = view.findViewById(R.id.chip_container);
    for(int i = 0; i < list.size(); i++){
    final View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_chip, null);
        ((TextView) view.findViewById(R.id.chip_text)).setText(list.get(i));
        linearLayout.addView(view);
    }
    

    background_chip.xml

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    
         <solid android:color="#cac8c8"/>
         <corners android:radius="20dp"/>
    </shape>