Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot set OnItemClickListener for spinner in android

In a customized RecyclerView.Adapter<CustomAdapter.ViewHolder>, I set an adapter for a spinner and found that the value of my spinner isn't change after selection, so I tried to add an OnItemClickListener on my spinner:

override fun onBindViewHolder(viewHolder: ViewHolder, position: Int) {

    // The selectable items of the spinner is dynamically generated from getItems() function
    val selectableItems: List<String> = getItems()

    val spinnerAdapter = ArrayAdapter<String>(this.context, androi.R.layout.simple_spinner_item)
    spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
    spinnerAdapter.addAll(selectableItems)

    viewHolder.mySpinner.adapter = spinnerAdapter

    // the error occurs on the following line:
    viewHolder.mySpinner.onItemClickListener = AdapterView.OnItemClickListener { adapterView, view, i, l ->
        adapterView.setSelection(i)
    }

    viewHolder.mySpinner.setSelection(origionSelectedPosition)
}

I didn't get any warning or error while compiling, however during run time, I got a RuntimeException said that setOnItemClickListener cannot be used with a spinner. It is kind of strange. Did I do anything wrong in my code? Or does anyone know why my spinner didn't change with the corresponding selection?

Further description for Kotlin solution:

I had ever tried to use onItemSelectedListener but failed to find a suitable way to use it in kotlin. But finally! The following code solved my problem:

    viewHolder.mySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

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

        }

        override fun onNothingSelected(parent: AdapterView<out Adapter>?) {

        }

    }
like image 460
whitney13625 Avatar asked Apr 21 '16 06:04

whitney13625


2 Answers

Following sasikumar's answer, I solved it in kotlin with the following code:

viewHolder.mySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {

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

    }

    override fun onNothingSelected(parent: AdapterView<out Adapter>?) {

    }

}
like image 98
whitney13625 Avatar answered Oct 02 '22 21:10

whitney13625


Use setOnItemSelectedListener instead of onItemClickListener.

viewHolder.mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    @Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

    }

    @Override
    public void onNothingSelected(AdapterView<?> parent) {

    }
});
like image 21
sasikumar Avatar answered Oct 02 '22 21:10

sasikumar