Kotlin构造函数ArrayAdapter无法识别

时间:2018-02-01 08:22:38

标签: android kotlin android-arrayadapter

我在Kotlin中扩展ArrayAdapter时遇到了问题。

这里是代码:

class SpinnerArrayAdapter(context: Context?, resource: Int, list: ArrayList<Pair<Long, String>>) : ArrayAdapter<Pair<Long, String>>(context, resource, list) {
    override fun getCount(): Int {
        return list.size //error list is unresolved
    }
}

修改 与ArrayAdapter扩展无关。我的问题是构造函数的理解。

3 个答案:

答案 0 :(得分:2)

我尝试了你的问题,我发现了同样的问题。

但是通过使用val关键字调用构造函数,它正在工作。

class SpinnerArrayAdapter(context: Context?, val resource: Int, val list: ArrayList<Pair<Long, String>>) : ArrayAdapter<Pair<Long, String>>(context, resource, list) {
    override fun getCount(): Int {
        return list.size
    }
}

无论如何,我不知道为什么在这种情况下需要val关键字。我会挖掘找到问题。

答案 1 :(得分:0)

class MainActivity : AppCompatActivity(),AdapterView.OnItemSelectedListener {

    var languages = arrayOf("English", "French", "Spanish", "Hindi", "Russian", "Telugu", "Chinese", "German", "Portuguese", "Arabic", "Dutch", "Urdu", "Italian", "Tamil", "Persian", "Turkish", "Other")

    var spinner:Spinner? = null
    var textView_msg:TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        textView_msg = this.msg

        spinner = this.spinner_sample
        spinner!!.setOnItemSelectedListener(this)

        // Create an ArrayAdapter using a simple spinner layout and languages array
        val aa = ArrayAdapter(this, android.R.layout.simple_spinner_item, languages)
        // Set layout to use when the list of choices appear
        aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        // Set Adapter to Spinner
        spinner!!.setAdapter(aa)

    }

    override fun onItemSelected(arg0: AdapterView<*>, arg1: View, position: Int, id: Long) {
        textView_msg!!.text = "Selected : "+languages[position]
    }

    override fun onNothingSelected(arg0: AdapterView<*>) {

    }
}

它可以帮到你,尝试一下。

答案 2 :(得分:0)

如果您没有将构造函数args声明为valvar,则只能在init块中访问它们,因为它们不是属性:

class Test(context: Context) {

    private lateinit var applicationContext: Context

    init {
        applicationContext = context.applicationContext
    }
}

如果您需要在init块之外访问它们,则应根据需要使用valvar将其标记为属性:

class Test(val context: Context) {

    private lateinit var applicationContext: Context

    fun test() {
        applicationContext = context.applicationContext
    }
}