0

我在实现recyclerView 的基本Android 应用程序中使用Anko。在该onCreateViewHolder()方法中,我收到一个编译时错误,说类型不匹配。以下代码中的其他一切都很好。

class ListAdapter(val arrayList: ArrayList<String> = ArrayList<String>()) : RecyclerView.Adapter<Holder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Holder? {

        //type Mismatch error required AnkoContext<ViewGroup> Found AnkoContext<Context>
        return Holder(ItemUI().createView(AnkoContext.create(parent!!.context)))

    }

    override fun onBindViewHolder(holder: Holder, position: Int) {
        val item = arrayList.get(position)
        holder.bind(item)
    }

    override fun getItemCount(): Int {
        return arrayList.size
    }

}

class ItemUI : AnkoComponent<ViewGroup> {
    override fun createView(ui: AnkoContext<ViewGroup>): View {
        return with(ui) {

            verticalLayout {
                lparams(width = matchParent, height = dip(48))
                horizontalPadding = dip(16)

                var name=textView {
                    id = 7
                    singleLine = true
                    textSize = 16f
                }
                name.onClick {
                    toast("Hi,  ${name.text}!")
                }
            }
        }
    }
}

class Holder(itemView: View) : RecyclerView.ViewHolder(itemView){
    val name: TextView = itemView.find(1)

    fun bind(nm: String) {
        name.text = nm
    }
}

如果我使用了错误的语法或执行错误,请告诉recyclerview

4

1 回答 1

2

很抱歉回答迟了,但只是浏览我的代码与 Anko 的 recyclerView 适配器我注意到AnkoContext只有以下签名的创建者:

AnkoContext.create(ctx: Context, owner: ViewGroup, setContentView: Boolean = false)
AnkoContext.create(ctx: Context, setContentView: Boolean = false)

当您弄错时,I​​DE(Android Studio)会在该行下划线。我用了第一个:

AnkoContext.create(parent!!.context, parent)
于 2017-04-10T13:46:34.960 回答