8
votes

Créer dynamiquement Choice Chip dans Android

J'utilise des composants matériels pour créer la puce Choice. J'ai suivi https://material.io/develop/android/components/chip/ document. Il y a assez de choses pour créer une puce en XML, mais je ne sais pas comment créer une puce de choix par programme.

J'ai utilisé le code suivant pour créer une puce de manière dynamique, mais il crée une puce d'action par défaut.

val chip = Chip(activity)
chip.text = ("Chip 1")
chipGpRow.addView(chip)


2 commentaires

Il ne semble pas y avoir de méthode singulière pour définir un style particulier sur une puce par programmation. Cependant, il s'agirait simplement de définir les propriétés individuelles pertinentes selon celles définies dans le style Choice ; par exemple, chip.checkable = true , etc. Vous pouvez trouver ces attributs et leurs valeurs ici: github.com/material-components/material-components-android/b‌ Lob /… .


Mike M. Merci. Cela fonctionne en définissant l'attribut qui définit dans le lien pour la puce de choix.


3 Réponses :


2
votes

Vous pouvez soit 1) créer une mise en page xml pour une puce qui a le style de choix et la gonfler dans le code, similaire à l'exemple ChipGroupDemoFragment dans le catalogue: github.com/material-components/material-components-android/blob /… 2) créer un thème personnalisé qui définit le chipStyle par défaut pour être @ style / Widget.MaterialComponents.Chip.Choice Je recommande le n ° 1 car il vous permet de créer dynamiquement des puces de styles multiples.


0 commentaires

10
votes

 entrez la description de l'image ici

voici mon code, j'espère que cela vous sera utile:

créer un élément xml pour les puces et ajouter le style que vous voulez comme ici style="@style/Widget.MaterialComponents.Chip.Choice"^

item_chip_category.xml

 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);
    }
}

activité. 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

<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" />


1 commentaires

Existe-t-il un moyen de le faire dans un adaptateur au lieu d'une activité?



13
votes

Consultez le commentaire de Mike .

Sinon, vous pouvez définir une mise en page simple (layout_chip_choice.xml) avec le Chip et le style:

val chip = inflater.inflate(R.layout.layout_chip_choice, chipGpRow, false) as Chip  
chip.text = ("Chip 1")
chipGpRow.addView(chip)

Puis utilisez dans votre code:

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


2 commentaires

J'aime vraiment cette réponse car je ne savais pas que vous pouviez créer des vues individuelles comme celle-ci par programme. Je me demandais simplement quel gonfleur devrais-je utiliser si je veux créer ma puce de manière dynamique, quelque part loin de onCreateView ?


Vous pouvez utiliser getLayoutInflater () dans votre Activité ou Fragment .