【发布时间】:2019-07-26 20:29:15
【问题描述】:
我有一个component_category_view.xml,其中一个 ChipGroup 在一个约束布局内初始化,其 ID 为 categoryList,
我正在运行下面的 CategoryView.kt 类来给它充气并用芯片动态更新它,我把它放在我的活动中。
class CategoryView @JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
init {
inflateLayout()
}
private fun inflateLayout() {
val inflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
inflater.inflate(R.layout.component_category_view, this, true)
}
fun updateCategories(categories: List<Category>){
categories.forEach {
var chipText = "${it.title.capitalize()} (${it.amount})"
val chip = Chip(this@CategoryView.context)
chip.text = chipText
chip.isCheckable = true
chip.chipBackgroundColor = null
categoryList.addView(chip)
}
}
}
但是,当我运行并且我的代码到达它使用类别列表调用 updateCategories 的部分时,会出现以下错误:
E/AndroidRuntime: 致命异常: main 进程:com.company.project,PID:8262 java.lang.ClassCastException:com.company.project.common.ui.CategoryView 不能转换为 com.google.android.material.chip.ChipGroup
component_category_view.xml 看起来像这样
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/layout_border_bottom">
<com.google.android.material.chip.ChipGroup
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
android:id="@+id/categoryList"/>
</androidx.constraintlayout.widget.ConstraintLayout>
【问题讨论】:
标签: android kotlin material-design androidx