How to use an ArrayAdapter in a Fragment with Kotlin

前端 未结 1 511
悲&欢浪女
悲&欢浪女 2020-12-19 10:09

I am trying to to create a Spinner inside a Fragment but I am getting error in the ArrayAdapter constructor call. I don\'t know why, b

相关标签:
1条回答
  • 2020-12-19 10:58

    The problem is in this constructor call:

    spinner.adapter = ArrayAdapter(
        this,
        R.layout.support_simple_spinner_dropdown_item,
        resources.getStringArray(R.array.atoms)
    ) as SpinnerAdapter
    

    The argument this must be a reference to a Context, and a Fragment is not a Context. In an Activity it works because an Activity is a Context.

    The solution is to replace this with activity:

    spinner.adapter = ArrayAdapter(
        activity,
        R.layout.support_simple_spinner_dropdown_item,
        resources.getStringArray(R.array.atoms)
    )
    
    0 讨论(0)
提交回复
热议问题