How to disable onItemSelectedListener to be invoked when setting selected item by code

后端 未结 12 1167
慢半拍i
慢半拍i 2021-02-02 08:05

Just wondering how you handle the following problem: a result is calculated depending on two spinners\' selected items. To handle the UI things, i.e. a user picks a new item in

12条回答
  •  闹比i
    闹比i (楼主)
    2021-02-02 08:25

    In my case, since I'm triggering spinner programmatically, then I just have to add spinnerSelected flag after spinner.performClick() like below.

    private var spinnerSelected = false
    
    someView.setOnClickListener {
        spinner.performClick()
        spinnerSelected = true
    }
    
    spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
        override fun onNothingSelected(parent: AdapterView<*>?) {
            // do nothing
        }
    
        override fun onItemSelected(
            parent: AdapterView<*>?,
            view: View?,
            position: Int,
            id: Long
        ) {
            if (spinnerSelected) {
                //... do something
    
                spinnerSelected = false
            }
          }
        }
    

提交回复
热议问题