Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ConstraintLayout with an option to grey out the entire content (disabled like)
package com.example.grayscaleexperiment
import android.content.Context
import android.graphics.Canvas
import android.graphics.ColorMatrix
import android.graphics.ColorMatrixColorFilter
import android.graphics.Paint
import android.util.AttributeSet
import androidx.constraintlayout.widget.ConstraintLayout
//origin: https://github.com/iabhishek1041/grayscale_experiment/blob/master/app/src/main/java/com/example/grayscaleexperiment/ConstraintLayoutWithDisableSupport.kt
class ConstraintLayoutWithDisableSupport @JvmOverloads constructor(
context: Context,
attrs: AttributeSet? = null,
defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {
var disabled = false
set(value) {
field = value
requestLayout()
}
private val paint = Paint()
init {
val cm = ColorMatrix()
cm.set(
floatArrayOf(
0.33f, 0.33f, 0.33f, 0f, 0f,
0.33f, 0.33f, 0.33f, 0f, 0f,
0.33f, 0.33f, 0.33f, 0f, 0f,
0f, 0f, 0f, 1f, 0f
)
)
paint.colorFilter = ColorMatrixColorFilter(cm)
}
override fun dispatchDraw(canvas: Canvas?) {
if (disabled) {
canvas?.saveLayer(null, paint)
}
super.dispatchDraw(canvas)
if (disabled) {
canvas?.restore()
}
}
override fun draw(canvas: Canvas?) {
if (disabled) {
canvas?.saveLayer(null, paint)
}
super.draw(canvas)
if (disabled) {
canvas?.restore()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment