我正在尝试编写一个通用适配器ListView
,允许使用 Anko DSL 作为项目的内容。代码如下所示。如您所见,有一个丑陋的补丁with(viewGroup!!.context)
可以使代码正常工作。它不像您看到的其他 Anko 示例。如果我删除该with
声明,我的应用程序将崩溃
FATAL EXCEPTION: java.lang.ClassCastException: android.widget.FrameLayout$LayoutParams cannot be cast to android.widget.AbsListView$LayoutParams
有什么办法可以避免这种with
说法吗?
import java.util.*
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
class AnkoAdapter(itemFactory: () -> AbstractList<Any>, viewFactory: (index: Int, items: AbstractList<Any>, view: View?, viewGroup: ViewGroup?) -> View): BaseAdapter() {
val viewFactory = viewFactory
val items: AbstractList<Any> by lazy { itemFactory() }
override fun getView(index: Int, view: View?, viewGroup: ViewGroup?): View {
return viewFactory(index, items, view, viewGroup)
}
override fun getCount(): Int {
return items.size
}
override fun getItem(index: Int): Any {
return items.get(index)
}
override fun getItemId(index: Int): Long {
return items.get(index).hashCode().toLong() + (index.toLong() * Int.MAX_VALUE)
}
}
// -------------
// In main acitivty.
...
val items = listOf<String>("Mary", "Lisa", "Cheryl", "Linda")
val buttonCaption = "..."
listView.adapter = AnkoAdapter({items as AbstractList<Any>}) {
index: Int, items: AbstractList<Any>, view: View?, viewGroup: ViewGroup? ->
with(viewGroup!!.context) {
linearLayout {
textView(items[index].toString())
button(buttonCaption)
}
}
}