Dynamically create Choice Chip in android
Asked Answered
P

6

16

I am using Material Components for creating the Choice chip. I have followed https://material.io/develop/android/components/chip/ document. There is enough stuff for creating a chip in XML but not get an idea of how to create choice chip programmatically.

I have used following code to creating chip dynamically but it creates action chip by default.

val chip = Chip(activity)
chip.text = ("Chip 1")
chipGpRow.addView(chip)
Phonometer answered 26/3, 2019 at 5:47 Comment(2)
It doesn't look like there's any singular method to set a particular style on a Chip programmatically. However, it would just be a matter of setting the individual relevant properties per those defined in the Choice style; e.g., chip.checkable = true, etc. You can find those attributes and their values here: github.com/material-components/material-components-android/blob/….Orientate
Mike M. Thanks. It works by setting the attribute which defines in the link for choice chip.Phonometer
D
24

Check the Mike comment.

Otherwise you can define a simple layout (layout_chip_choice.xml) with the Chip and the style:

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

Then use in your code:

val chip = inflater.inflate(R.layout.layout_chip_choice, chipGpRow, false) as Chip  
chip.text = ("Chip 1")
chipGpRow.addView(chip)
Daric answered 5/10, 2019 at 10:17 Comment(2)
I really like this answer as I didn't know you could programatically create individual views like this. I was just wondering, which inflater should I use if I want to create my Chip dynamically, somewhere away from the onCreateView?Woehick
You can use getLayoutInflater() in your Activity or Fragment.Daric
F
18

enter image description here

following is my code, hope its useful to you :

create item xml for chips and add style that you want like here style="@style/Widget.MaterialComponents.Chip.Choice"

item_chip_category.xml

<com.google.android.material.chip.Chip xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:fontFamily="@font/popin"
android:gravity="center"
android:paddingLeft="8dp"
android:paddingRight="8dp"
style="@style/Widget.MaterialComponents.Chip.Choice"
android:textAppearance="?android:attr/textAppearance"
android:textColor="@color/secondaryTextColor"
app:chipBackgroundColor="@color/colorAccent" />

activity.xml

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:fontFamily="@font/popin"
            android:padding="8dp"
            android:text="Python Progrgrams"
            android:textAlignment="center"
            android:textAppearance="@style/TextAppearance.AppCompat.Medium"
            android:textColor="@color/secondaryTextColor"
            android:textStyle="bold" />

            <com.google.android.material.chip.ChipGroup
                android:id="@+id/chipsPrograms"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="@dimen/text_margin"
                android:paddingStart="@dimen/text_margin"
                android:paddingEnd="@dimen/text_margin"
                app:chipSpacing="8dp"
                app:singleSelection="false">

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

    </LinearLayout>

Activity.java

 public void setCategoryChips(ArrayList<String> categorys) {
    for (String category :
            categorys) {
        Chip mChip = (Chip) this.getLayoutInflater().inflate(R.layout.item_chip_category, null, false);
        mChip.setText(category);
        int paddingDp = (int) TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_DIP, 10,
                getResources().getDisplayMetrics()
        );
        mChip.setPadding(paddingDp, 0, paddingDp, 0);
        mChip.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {

            }
        });
        chipsPrograms.addView(mChip);
    }
}
First answered 2/8, 2019 at 6:34 Comment(1)
Is there a way to do this in an Adapter instead of an Activity?Frenum
G
4

You could either 1) create an xml layout for a chip that has the choice style and inflate it in code, similar to the ChipGroupDemoFragment example in the catalog: github.com/material-components/material-components-android/blob/… 2) create a custom theme that sets the default chipStyle to be @style/Widget.MaterialComponents.Chip.Choice I recommend #1 because it allows you the flexibility of dynamically creating chips of multiple styles.

Gamboa answered 28/3, 2019 at 21:7 Comment(0)
N
1

XML

 <com.google.android.material.chip.ChipGroup
   android:id="@+id/chipGroupEmail"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"/>

Activity.java

 //init
    ChipGroup chipGroupEmail = findViewById(R.id.chipGroupEmail);


//create a function
     private void funAddChip(String name) {
        
                Chip chip = new Chip(requireContext());
                chip.setText(name);
                chip.setCloseIconVisible(true);
                chip.setMinWidth(100);
                chip.setOnCloseIconClickListener(view -> {
                  
                    try {
                        chipGroupEmail.removeView(view);
                        
                    } catch (Exception e) {
                        Utils.Log_d("funAddChip Exception:-" + e);
                    }
        
                });
                chipGroupEmail.addView(chip);
            }
Neri answered 9/2, 2023 at 6:4 Comment(0)
C
0

I don't like the comment on setting the checkable attribute manually instead of the stylistic way. You lose other attributes, like ripple color and state list animator. Inflating a layout with your chip defined and including the style attribute with choice is the only way to do it as of now.

I have been trying to apply a style to a Chip created programmatically with context theme wrapper. This seems like the way to go, but Chip as an extension of AppCompatCheckBox does not define the four-argument constructor where the default style (action) could be overwritten with choice in my case. So the chip is always of type action ><.

Crosier answered 5/2, 2021 at 17:41 Comment(0)
G
0

Add chip to chip group in dynamically of single choice style using inflating chip layout file.

Single Chip layout:

    <com.google.android.material.chip.Chip 
    xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/ChipStyle"`enter code here`
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Single Choice Style:

     <style name="ChipStyle" parent="Widget.MaterialComponents.Chip.Choice">
        <item 
        name="chipBackgroundColor">@color/state_choice_chip_background_color</item>
        <item name="android:textColor">@color/white</item>
        <item name="checkedIconEnabled">false</item>
        <item name="checkedIcon">@null</item>
    </style>

state_choice_chip_background_color.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:color="@color/red" android:state_checked="true" />
    <item android:color="@color/black" />
</selector>

Method to add chips to group:

    private fun addChipToGroup(person: AllQuestionData) {
        val chip =LayoutInflater.from(context).inflate(R.layout.chip, 
        binding.chipGroup, false) as Chip
        chip.text = ("Chip 1")
        chip.text = person.sectionName
        chip.isClickable = true
        chip.isCheckable = true
        chip.isChipIconVisible = false
        chip.isCheckedIconVisible = false
        binding.chipGroup.addView(chip as View)
        chip.setOnClickListener {
            viewModel.setSwipeTabs(person)
        }
    }

OR

Add chip to chip group in dynamically of single choice style without inflating chip layout file. directly add style selected chip color or style

        private fun addChipToGroup(person: AllQuestionData) {
        val chip = Chip(context,null, com.google.android.material.
        R.style.Widget_MaterialComponents_Chip_Choice)
        chip.text = ("Chip 1")
        chip.text = person.sectionName
        chip.isClickable = true
        chip.isCheckable = true
        chip.isChipIconVisible = false
        chip.isCheckedIconVisible = false
        chip.setChipBackgroundColorResource
        (R.color.state_choice_chip_background_color)
        chip.setTextColor(ContextCompat.getColor(requireContext(), R.color.white))
        binding.chipGroup.addView(chip as View)
        chip.setOnClickListener {
            viewModel.setSwipeTabs(person)
        }
    }


   
Garthgartner answered 21/3 at 7:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.