Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android chips taking extra spaces;unable to wrap

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.

like image 535
adi Avatar asked Dec 13 '22 11:12

adi


2 Answers

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

chip.setChipStartPadding(0);
chip.setChipEndPadding(0);
like image 137
JiajiaGu Avatar answered Dec 30 '22 07:12

JiajiaGu


For chips, it's not (inner) "padding", but (outer) "spacing":

  • app:chipSpacing  —  Adds spacing to both the horizontal and vertical axis.
  • app:chipSpacingHorizontal  —  Adds spacing to the horizontal axis.
  • app:chipSpacingVertical  —  Adds spacing to the vertical axis.

the least spacing with line-wrapping would be:

app:singleLine="false"
app:chipSpacing="0dp"

alternatively, wrap the ChipGroup in a HorizontalScrollView with app:singleLine="true".

like image 25
Martin Zeitler Avatar answered Dec 30 '22 05:12

Martin Zeitler