Change Switch state without animation

前端 未结 7 1947
醉酒成梦
醉酒成梦 2020-12-09 07:54

In my Android project, I have a ListView with rows containing SwitchCompat items (AppCompat for Switch widget).

My problem occ

7条回答
  •  臣服心动
    2020-12-09 08:15

    In my case, I am using the new material library:

    implementation 'com.google.android.material:material:1.1.0-alpha07'
    

    and in the setChecked method of this class there is this condition:

    if (getWindowToken() != null && ViewCompat.isLaidOut(this))
    

    So what I did was to create a class that extends from this SwitchMaterial, and deal with "isLaidOut". The code is the next one (omitting constructors):

    class SwitchCustomView : SwitchMaterial {
    
      private var laidOutForAnimation = false
    
      fun setChecked(checked: Boolean, animate: Boolean) {
        if (!animate) {
          laidOutForAnimation = true
        }
        super.setChecked(checked)
        laidOutForAnimation = false
      }
    
      override fun isLaidOut(): Boolean {
        return if (laidOutForAnimation) {
          return false
        } else {
          super.isLaidOut()
        }
      }
    }
    

    Then just use this class in your xml and call programatically

    setChecked(checked: Boolean, animate: Boolean)
    

提交回复
热议问题