问题
I am trying to make a Chip Selection which will have multiple choices. In my case I will have choices dynamically so I will have to create chips dynamically. I was successfully able to create it dynamically. But as multi selection needs a property called style="@style/Widget.MaterialComponents.Chip.Filter"
I am able to pass this in XML but not in kotlin code.
I tried to do like this but didn't succeed:
val chip = Chip(chapManager.context, null, android.widget.Filter)
It says: Classifier 'Filter' does not have a companion object, and thus must be initialized here
Everything else works fine, just I'm not able to pass style to my chip.
回答1:
You can define separate layout for Chip
and setting all the attributes you want in XML
, then inflate the layout.
val chip = layoutInflater.inflate(R.layout.chip_layout, view!!.parent.parent as ViewGroup, false) as Chip
chip_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.chip.Chip xmlns:android="http://schemas.android.com/apk/res/android"
style="@style/Widget.MaterialComponents.Chip.Filter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="@style/chipTextAppearance"
android:textColor="@android:color/black" />
来源:https://stackoverflow.com/questions/53703999/add-filterchips-programmatically-in-android