I am making a program which includes a spinner and i need that when you select an item from the spinner it shows it in a text view. This is the code i have so far:
val spinner_1 = findViewById<Spinner>(R.id.drop_1)
if (spinner_1 != null) {
val adapter = ArrayAdapter(this,
android.R.layout.simple_spinner_item, lands)
spinner_1.adapter = adapter}
var text = ""
text = spinner_1.getSelectedItem().toString()
val choice = findViewById<View>(R.id.textView_choice) as TextView
choice.setText(text)
I think i did something wrong with text = spinner_1.getSelectedItem().toString()
. What should i do?
CodePudding user response:
In Kotlin its works like that.
yourSpinner?.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
val selectedItem = parent.getItemAtPosition(position).toString()
choice.setText(selectedItem)
}
}
CodePudding user response:
You need to add onItemSelectedListener on spinner like this
spinner.onItemSelectedListener = this
and then, need to implement its method
override fun onItemSelected(parent: AdapterView<*>, view: View?, pos: Int, id: Long) {
// On selecting a spinner item
String item = parent.getItemAtPosition(pos).toString();
// Showing selected spinner item
Toast.makeText(parent.getContext(), "Selected: " item, Toast.LENGTH_LONG).show()
}
override fun onNothingSelected(parent: AdapterView<*>) {
// TODO Auto-generated method stub
}