Skip to content

Instantly share code, notes, and snippets.

@abhimuktheeswarar
Created June 26, 2020 05:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abhimuktheeswarar/615246bf3ecc7e49f385736302b1fdef to your computer and use it in GitHub Desktop.
Save abhimuktheeswarar/615246bf3ecc7e49f385736302b1fdef to your computer and use it in GitHub Desktop.
A ConstraintLayout that implements Checkable interface
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