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:
I want the chip to use as minimal width as possible according to its text.
You should set padding for chip in right way, try this:
chip.setChipStartPadding(0);
chip.setChipEndPadding(0);
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With