因此,我正在学习kotlin,现在我需要编写一个ArrayAdapter,但是在尝试执行此操作时出现了一些错误:

convertView = vi.inflate(resource, null)

Kotlin 告诉我



在站点kotline中,我将java类转换为kotlin类,并尝试在此站点中进行操作。为什么会出现错误,我该如何解决?这是完整的代码。
open class MyAdapter(context: Context, resource: Int, list: ArrayList<MyItems>) :
        ArrayAdapter<MyItems>(context, resource, list) {

    var resource: Int
    var list: ArrayList<MyItems>
    var vi: LayoutInflater

    init {
        this.resource = resource
        this.list = list
        this.vi = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
    }


    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
        var holder: ViewHolder

        if(convertView == null){
            convertView = vi.inflate(resource, null) //error in this line
            holder = ViewHolder()

            holder.image = convertView.findViewById(R.id.myImage) as ImageView?

            convertView.tag(holder) //error in this line

        } else {
            holder = convertView.tag as ViewHolder
        }

        return convertView
    }

    internal class ViewHolder {
        var image: ImageView? = null
    }

}

最佳答案

无法重新分配参数变量,您将需要创建一个局部变量来保存返回的 View :

override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {
    var holder: ViewHolder
    var retView: View

    if(convertView == null){
        retView = vi.inflate(resource, null)
        holder = ViewHolder()

        holder.image = retView.findViewById(R.id.myImage) as ImageView?

        retView.tag = holder

    } else {
        holder = convertView.tag as ViewHolder
        retView = convertView
    }

    return retView
}

关于android - ArrayAdapter使用Kotlin android,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41923557/

10-12 04:02
查看更多