Skip to content

Instantly share code, notes, and snippets.

@JulienArzul
Last active May 25, 2022 00:34
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JulienArzul/8068d43af3523d75b72e9d1edbfb4298 to your computer and use it in GitHub Desktop.
Save JulienArzul/8068d43af3523d75b72e9d1edbfb4298 to your computer and use it in GitHub Desktop.
ConstraintLayoutAccessibilityHelper
package com.julienarzul.android.accessibility
import android.content.Context
import android.os.Build
import android.util.AttributeSet
import android.view.View
import android.view.accessibility.AccessibilityEvent
import androidx.constraintlayout.widget.ConstraintHelper
import androidx.constraintlayout.widget.ConstraintLayout
class ConstraintLayoutAccessibilityHelper
@JvmOverloads constructor(
context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : ConstraintHelper(context, attrs, defStyleAttr) {
init {
importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_YES
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
isScreenReaderFocusable = true
} else {
isFocusable = true
}
}
override fun updatePreLayout(container: ConstraintLayout) {
super.updatePreLayout(container)
if (this.mReferenceIds != null) {
this.setIds(this.mReferenceIds)
}
mIds.forEach {
container.getViewById(it)?.importantForAccessibility = View.IMPORTANT_FOR_ACCESSIBILITY_NO
}
}
override fun onPopulateAccessibilityEvent(event: AccessibilityEvent) {
super.onPopulateAccessibilityEvent(event)
val constraintLayoutParent = parent as? ConstraintLayout
if (constraintLayoutParent != null) {
event.text.clear()
mIds.forEach { id ->
val view: View? = constraintLayoutParent.getViewById(id)
// Adds this View to the Accessibility Event only if it is currently visible
if (view?.isVisible == true) {
view.onPopulateAccessibilityEvent(event)
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment