0

我正在尝试编写一个通用适配器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)
        }
    }
}
4

1 回答 1

0

根据此视频,这是修改后的版本:

class AnkoAdapter<T>(itemFactory: () -> List<T>, viewFactory: Context.(index: Int, items: List<T>, view: View?) -> View): BaseAdapter() {
    val viewFactory = viewFactory
    val items: List<T> by lazy { itemFactory() }

    override fun getView(index: Int, view: View?, viewGroup: ViewGroup?): View {
        return viewGroup!!.context.viewFactory(index, items, view)
    }

    override fun getCount(): Int {
        return items.size
    }

    override fun getItem(index: Int): T {
        return items.get(index)
    }

    override fun getItemId(index: Int): Long {

        return (items.get(index) as Any).hashCode().toLong() + (index.toLong() * Int.MAX_VALUE)
    }
}

val items = listOf<String>("Mary", "Lisa", "Cheryl", "Linda")
val buttonCaption = "..."
lockView.adapter = AnkoAdapter<String>({ items }) {
    index, items, view ->
    linearLayout {
        textView(items[index])
        button(buttonCaption)
    }
}
于 2016-09-13T17:52:36.853 回答