3

我相信答案是肯定的,因为我可以在这里看到 react 的答案,但我不知道如何在 Kotlin/Java 中做到这一点。我看到的唯一选项是setChipBackgroundColorResourcesetBackgroundColor两者都需要颜色资源。如何使用渐变作为背景?

  • 我知道如何为任何常规视图设置背景,但只是芯片有问题。我已经尝试过了,chip.setBackgroundResource(R.drawable.gradient_background)但它只会使背景变灰
4

2 回答 2

3

目前你不能这样做

  • 该方法setChipBackgroundColorResource适用于colordrawable
  • 该方法setChipBackgroundColor正在使用ColorStateList
  • 方法 ,只会产生警告setBackgroundResourcesetBackgroundDrawablesetBackgroundDo not set the background; Chip manages its own background drawable.

这是因为 Chip 小部件是围绕ChipDrawable. ChipDrawable 只是一个MaterialShapeDrawable管理它的背景的东西,比如:

* chipStartPadding iconEndPadding closeIconStartPadding chipEndPadding
 * + + + +
 * | | | |
 * | iconStartPadding | textStartPadding textEndPadding | closeIconEndPadding |
 * | + | + + | + |
 * | | | | | | | |
 * vvvvvvvv
 * +-----+----+------------+----+----+--------------- ------+----+----+----------+----+-----+
 * | | | XX | | | XX XXX XXX | | | XX | | |
 * | | | XX | | | XXXXXXX | | | XX XX | | |
 * | | | XX XX | | | X XXXX X XXX | | | XX | | |
 * | | | XXX | | | XXXXXX | | | XX XX | | |
 * | | | X | | | XX XXXX | | | XX | | |
 * +-----+----+------------+----+----+--------------- ------+----+----+----------+----+-----+
 * ^ ^ ^
 * | | |
 * + + +
 * chipIconSize *动态* closeIconSize
 *
于 2019-10-05T06:42:34.010 回答
0

It is not possible to set a background to Chip rather you can set the rounded corners or colors to it. You can also give a border color.

According to the documentation,

All attributes from Chip are supported. Do not use the android:background attribute. It will be ignored because Chip manages its own background Drawable. Also do not use the android:drawableStart and android:drawableEnd attributes.

Hence if you are looking something to give corners or a chip with a different border color I would suggest you to try this,

    Chip chip = new Chip(Activity.this);
    chip.setText("Holiday");
    chip.setCloseIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.close_chip, null));
    chip.setCloseIconTint(ColorStateList.valueOf(Color.parseColor("#aa99bc")));
    chip.setPadding(5, 5, 5, 5);  
    chip.setCloseIconVisible(true);
    chip.setTextAppearanceResource(R.style.ChipTextStyle);
    chip.setChipStrokeColorResource(R.color.chip_border_color);
    chip.setChipStrokeWidth(1);
    chip.setChipCornerRadius(30);                                          
    chip.setChipBackgroundColorResource(R.color.chip_background);
于 2019-08-14T04:25:45.780 回答