0

I want to set the event after the initial value has been set. I have tried to set the event handler onStart(), but it seems that the event is still called for the initial value set, which was don in onCreate(). Is there a way to set it after the initial value has been set?

class MainActivity : Activity()
{
  lateinit var spinner:Spinner;
  override fun onCreate(savedInstanceState: Bundle?)
  {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    spinner = findViewById<Spinner>(R.id.spinner);
    spinner.setSelection(2);
  }

  override fun onStart()
  {
    super.onStart()
    spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
      override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long)
      {
        Log.d("stack", "onItemSelected($position)");
      }

      override fun onNothingSelected(parent: AdapterView<*>?)
      {
        Log.d("stack", "onNothingSelected");
      }
    }
  }
}

Output:

D/stack: onItemSelected(2)
Damn Vegetables
  • 11,484
  • 13
  • 80
  • 135
  • If you are trying to avoid getting the callback to that on initial load then the only really reliable thing to do is use a boolean flag and flip it after the first callback so you know when to process the callback – tyczj Jan 04 '22 at 21:23
  • 1
    https://stackoverflow.com/a/17336944/2711811 - use 2nd parameter –  Jan 04 '22 at 21:36

0 Answers0