onItemSelected不会被调用。

问题描述 投票:0回答:1

实现android网站上的基本spinner例子不会调用onItemSelected。在StackOverflow上看了25个答案后,我还没有找到解决方案。我可以看到微调器上的选项,但是当我选择一个选项时,什么都没有发生,下面是代码。

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

    val text = findViewById<TextView>(R.id.textView)
    val spinner: Spinner = findViewById(R.id.spinner)

    // Create an ArrayAdapter using the string array and a default spinner layout
    ArrayAdapter.createFromResource(
        this,
        R.array.sources,
        android.R.layout.simple_spinner_item
    ).also { adapter ->
        // Specify the layout to use when the list of choices appears
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
        // Apply the adapter to the spinner
        spinner.adapter = adapter
    }

    class SpinnerActivity : Activity(), AdapterView.OnItemSelectedListener {

        override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) {

            Log.d("nothing", "happending")

            when (parent.getItemAtPosition(pos).toString()){
                "file 1" -> Log.d("Selection","file 1")
                "file 2" -> Log.d("selection", "file 2")
                else -> text.append("No match")
            }

            Toast.makeText(applicationContext,"Called made",Toast.LENGTH_LONG).show()
        }

        override fun onNothingSelected(parent: AdapterView<*>) {
            // Another interface callback
        }
    }

}

}

android spinner
1个回答
0
投票

与其创建内部类SpinnerActivity,你应该在spinner上注册监听器。

    spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onItemSelected(parent: AdapterView<*>, view: View, pos: Int, id: Long) {

            Log.d("nothing", "happending")

            when (parent.getItemAtPosition(pos).toString()){
                "file 1" -> Log.d("Selection","file 1")
                "file 2" -> Log.d("selection", "file 2")
                else -> text.append("No match")
            }

            Toast.makeText(applicationContext,"Called made",Toast.LENGTH_LONG).show()
        }

        override fun onNothingSelected(parent: AdapterView<*>) {
            // Another interface callback
        }
    }
© www.soinside.com 2019 - 2024. All rights reserved.