Add FilterChips programmatically in Android

江枫思渺然 提交于 2019-12-24 10:20:04

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!