Accessibility and Fragment transactions
Making sure your app is accessible is something we often forget about.
Try to think about a disabled person trying to use your app, and not being able to do so because of your code. Doesn’t feel good, right?
There are many tutorials online to help you make your app accessible, but I found a case where no tutorial helped. It involves.. what else than Fragments.
When adding a fragment (instead of replacing), the accessibility focus remains on the old fragment view, and not on the newly added one that is on top.
After trying many methods to resolve this issue, I found something that worked for me, and I want to share it.
The trick is to change the
importantForAccessibility flag value for the fragments views after the back stack has changed.
I created an extension function for
FragmentManager. Whenever there’s a change in the back stack, we’re finding the top fragment view, marking it as important for accessibility, and marking all other views as not:
Then I call this extension function from the
onCreate callbacks inside my base Activity and base Fragment:
And that’s it, you’re good to go!