Scenario: I am using Spinner for date range selection, which is working perfectly. The issue is, there is an option "Custom Range" on which I have to open a custom date range picker. Although it is working fine for the first time.
The issue is:
When users click it again, it doesn't call onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long)
(which is a functionality of Spinner). But from the user point of view, it's a bug.
Is there any way, we can get any selection event on an already selected item of Spinner?
To call an event on the already selected item in Spinner
You can do it in this way:
AppCompatSpinner
:import android.content.Context
import android.util.AttributeSet
import android.util.Log
class MySpinner(context: Context, attrs: AttributeSet?) : androidx.appcompat.widget.AppCompatSpinner(
context,
attrs
)
{
var listener: OnItemSelectedListener? = null
override fun setSelection(position: Int)
{
super.setSelection(position)
if (position == selectedItemPosition)
{
listener!!.onItemSelected(this, selectedView, position, selectedItemId)
}
}
override fun setOnItemSelectedListener(listener: OnItemSelectedListener?)
{
this.listener = listener
}
}
<com.yourcompany.kotlintest.MySpinner
android:id="@+id/spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
class MainActivity : AppCompatActivity()
{
override fun onCreate(savedInstanceState: Bundle?)
{
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val spinner = findViewById<MySpinner>(R.id.spinner)
spinner.adapter = ArrayAdapter(
this,
android.R.layout.simple_spinner_dropdown_item,
arrayListOf("One", "Two", "Three")
)
spinner.onItemSelectedListener = object :
AdapterView.OnItemSelectedListener
{
override fun onItemSelected(
parent: AdapterView<*>,
view: View, position: Int, id: Long
)
{
Log.d("MyTag", "Click item at pos $position")
}
override fun onNothingSelected(parent: AdapterView<*>)
{
Log.d("MyTag", "Nothing selected")
}
}
}
}
Now when You reselect the same item function will be executed