Spinner's onItemSelected callback called twice after a rotation if non-zero position is selected

后端 未结 8 1189
执念已碎
执念已碎 2021-02-03 20:52

When I create my activity, I setup a Spinner, assigning it a listener and an initial value. I know that the onItemSelected callback is called automatically during a

8条回答
  •  旧巷少年郎
    2021-02-03 21:11

    I am updating @Andres Q.'s answer in Kotlin.

    Create an inner class in which you're using Spinner

    inner class SpinnerInteractionListener : AdapterView.OnItemSelectedListener, View.OnTouchListener {
            override fun onNothingSelected(parent: AdapterView<*>?) {
    
            }
    
            override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
                if (userSelect) {
                    //Your selection handling code here
                    userSelect = false
                }
            }
    
            @SuppressLint("ClickableViewAccessibility")
            override fun onTouch(v: View?, event: MotionEvent?): Boolean {
                userSelect = true
                return false
            }
    
            internal var userSelect = false
        }
    

    Then declare instance variable outside onCreate() as globally like

    lateinit var spinnerInteractionListener: SpinnerInteractionListener
    

    then initialise it inside onCreate() by

    spinnerInteractionListener = SpinnerInteractionListener()
    

    and use it like

    spinnerCategory.onItemSelectedListener = spinnerInteractionListener
    spinnerCategory.setOnTouchListener(spinnerInteractionListener)
    

    here spinnerCategory is Spinner

提交回复
热议问题