【问题标题】:How to apply a `style` for a chip in code? [duplicate]如何在代码中为芯片应用“样式”? [复制]
【发布时间】:2019-03-23 21:25:32
【问题描述】:

在我的 xml 布局中,我有一个带有过滤芯片的芯片组。

<android.support.design.chip.ChipGroup
    android:id="@+id/chipGroup"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.design.chip.Chip
        style="@style/myStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    .....

</android.support.design.chip.ChipGroup>

由于有很多过滤器,在代码中添加它们似乎是合理的。问题是我需要将style 属性应用于每个芯片。

我试过了:

val chip = Chip(ContextThemeWrapper(context, R.style.myStyle))
binding.chipGroup.addView(chip)

没有效果

val chip = Chip(context, null, R.style.myStyle)
binding.chipGroup.addView(chip)

没有效果

我创建了layout/filter_chip.xml 并放了一个芯片模板

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.chip.Chip 
    xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/myStyle"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

我用这样的代码创建它

val chip = inflater.inflate(R.layout.filter_chip, binding.chipGroup, false) as Chip   
binding.chipGroup.addView(chip)

它有效并且应用了样式。但我问自己这是否真的是实现它的最简单方法。你知道更好的吗?

【问题讨论】:

    标签: android android-chips


    【解决方案1】:

    我认为您可以使用ContextThemeWrapper,方法是创建具有您想要的样式的 ContextThemeWrapper,然后将主题上下文传递给芯片的构造函数。

    【讨论】:

    • 他说试过了,但是没有效果。我也面临这个问题,没有任何效果。
    猜你喜欢
    • 1970-01-01
    • 2019-07-31
    • 2021-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    相关资源
    最近更新 更多