0

我创建了一个自定义微调器适配器,它返回两个视图(item_new_area 和 item_area),item_new_area 是静态的,带有选项 Add New 和 item_area 填充动态。

在此处输入图像描述

选择添加新时,我想启动添加新区域的对话框,但我不断收到一个错误,即lateinit 属性侦听器尚未初始化

自定义微调器适配器

class AreaSpinnerAdapter(private val inflater: LayoutInflater) : BaseAdapter() {
var areas: List<AreaEntity>? = null
lateinit var listener: OnItemSelectedListener

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

    return when (getItemViewType(position)) {
        1 -> {
            val binding: ItemNewAreaBinding = DataBindingUtil.inflate<ItemNewAreaBinding>(
                inflater,
                R.layout.item_new_area,
                parent, false
            ).also {
                it.root.tag = it
            }

            binding.addNew.setOnClickListener {
                listener.onClick()

            }
            binding.root
        }
        else -> {
            val binding: ItemAreaBinding = DataBindingUtil.inflate<ItemAreaBinding>(
                inflater,
                R.layout.item_area,
                parent, false
            ).also {
                it.root.tag = it
            }
            binding.area = getItem(position)
            binding.root
        }
    }
}

override fun getItemViewType(position: Int): Int {
    return if (position == 1) {
        1
    } else {
        2
    }
}

fun setOnItemClickListener(listener: OnItemSelectedListener) {
    this.listener = listener
}


interface OnItemSelectedListener {
    fun onClick()
}

}

我尝试在我的片段的 onCreateView 方法中设置 on Item Clicked 侦听器:

val spinnerAdapter = AreaSpinnerAdapter(layoutInflater)
    spinnerAdapter.setOnItemClickListener(object :
        AreaSpinnerAdapter.OnItemSelectedListener {
        override fun onClick() {
            addNewAreaDialog()
        }
    })

    binding?.spinnerArea?.adapter = spinnerAdapter

错误日志

 kotlin.UninitializedPropertyAccessException: lateinit property listener has not been initialized
    at com.test.adapter.AreaSpinnerAdapter.getListener(AreaSpinnerAdapter.kt:15)
    at com.test.adapter.AreaSpinnerAdapter$getView$1.onClick(AreaSpinnerAdapter.kt:50)

第 15 行 = lateinit var 监听器:OnItemSelectedListener

第 25 行 = listener.onClick()

我知道应该在调用 getView 方法之前初始化侦听器,但由于某些原因无法初始化侦听器,任何有关如何执行此操作的帮助将不胜感激。谢谢

4

1 回答 1

1

您需要将侦听器移动AreaSpinnerAdapter到构造函数。

class AreaSpinnerAdapter(
    private val inflater: LayoutInflater,
    private val listener: OnItemSelectedListener
        ) : BaseAdapter() {
    var areas: List<AreaEntity>? = null

然后像这样称呼它

val spinnerAdapter = AreaSpinnerAdapter(layoutInflater, 
object: AreaSpinnerAdapter.OnItemSelectedListener {
    override fun onClick() {
        addNewAreaDialog()
    }
})
于 2020-07-02T07:37:48.500 回答