Created
June 26, 2020 05:47
-
-
Save abhimuktheeswarar/615246bf3ecc7e49f385736302b1fdef to your computer and use it in GitHub Desktop.
A ConstraintLayout that implements Checkable interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.yourcompany.name | |
import android.content.Context | |
import android.util.AttributeSet | |
import android.view.View | |
import android.widget.Checkable | |
import androidx.constraintlayout.widget.ConstraintLayout | |
class CheckableConstraintLayout @JvmOverloads constructor( | |
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0 | |
) : ConstraintLayout(context, attrs, defStyleAttr), Checkable { | |
private var checked = false | |
override fun setChecked(checked: Boolean) { | |
this.checked = checked | |
refreshDrawableState() | |
} | |
override fun isChecked(): Boolean { | |
return checked | |
} | |
override fun toggle() { | |
isChecked = !checked | |
refreshDrawableState() | |
} | |
override fun onCreateDrawableState(extraSpace: Int): IntArray { | |
val drawableState = super.onCreateDrawableState(extraSpace + 1) | |
if (isChecked) { | |
View.mergeDrawableStates( | |
drawableState, | |
CheckedStateSet | |
) | |
} | |
return drawableState | |
} | |
override fun performClick(): Boolean { | |
toggle() | |
return super.performClick() | |
} | |
companion object { | |
private val CheckedStateSet = intArrayOf( | |
android.R.attr.state_checked | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment