[SOLVED] android chips taking extra spaces;unable to wrap


This Question and Answer are collected from stackoverflow and tested by JTuto community, is licensed under
CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

Issue

I use chipgroup with dynamic chips. I want the chips to get wrapped in width according to their text. But it takes extra spaces even without padding.

Below is my code:

xml:

<com.google.android.material.chip.ChipGroup
    android:id="@+id/cg"
    android:layout_width="0dp"
    android:layout_weight="75"
    android:layout_height="wrap_content"
    android:layout_marginTop="20dp"
    android:layout_marginBottom="5dp"
    android:textColor="@android:color/black"
    android:textStyle="bold"
    android:textSize="12sp"
    app:singleSelection="false"
    app:chipSpacingVertical="5dp"
    app:chipSpacingHorizontal="5dp"
    app:singleLine="false"
    app:chipSpacing="2dp">

This is how to add chips dynamically:

for(int i=0;i<cartoonTypes.length;i++){
    chip = new Chip(this);
    chip.setText(cartoonTypes[i].trim());
    chip.setTextColor(Color.WHITE);
    chip.setChipBackgroundColor(getResources().getColorStateList(R.color.colorChip));
    chip.setTextSize(12);
    chip.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL);
    chip.setPadding(0,0,0,0);
    cgMovieGenre.addView(chip);
    ChipGroup.LayoutParams layoutParams = (ChipGroup.LayoutParams) chip.getLayoutParams();;
    int dpSize = px2dp(12);;
    layoutParams.height = dpSize;
    layoutParams.width = ChipGroup.LayoutParams.WRAP_CONTENT;
    chip.setLayoutParams(layoutParams);
}

method px2dp does this:

int px2dp(int px){
    metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int h = (px * metrics.densityDpi) / DisplayMetrics.DENSITY_DEFAULT;
    return h;
}

My build.gradle has the following dependencies:

implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.0.0-beta01'
implementation 'androidx.cardview:cardview:1.0.0-beta01'
implementation 'com.google.android.material:material:1.0.0-beta01'

This is what I see:

screenshot, chip-group

I want the chip to use as minimal width as possible according to its text.

Solution

You should set padding for chip in right way, try this:

chip.setChipStartPadding(0);
chip.setChipEndPadding(0);

Answered By – JiajiaGu

people found this article helpful. What about you?