How to make your Kotlin Android animations accessible

How to make your Kotlin Android animations accessible

<strong>When researching examples for a first ever Android contribution, few examples existed for animations written in Kotlin. There were also few code examples of accessibility considerations within native animations.</strong>

When researching examples for a first ever Android contribution, few examples existed for animations written in Kotlin. There were also few code examples of accessibility considerations within native animations.

So here we go! Let’s look at writing a native ‘expand’ animation in Kotlin, and talk about how to assist those with TalkBack or enlarged text turned on. All code is available in this example repo, creating a single activity with an animated view within it. The code this is based on was co-written with Calum Turner.

Android accessibility (a11y)

All Android devices come with a built in screen reader named TalkBack. This can be turned on from the device’s settings, and also has a first time use guide built in. Gestures are used to navigate around the page, with descriptions of focused elements read aloud. Without this, an app becomes unusable for many visually impaired users.

Of key importance is that the correct elements are focusable, have descriptions, and changes to the view are announced.

Within the same settings menu the default base font size can be adjusted, scaling from 1.0. Views should react to this change in font size, with all elements still present and functioning.


We won’t look at the styling specifics of the layout here as they are fairly unique to this example, but the accessibility touches are worth highlighting.

Two properties are used: android:contentDescription and android:importantForAccessibility.

The contentDescription is what is read when an element gains focus. For any ImageView that gains focus this is essential, otherwise a screen reader will instead read the useless ‘unlabelled’ to the user.

If this was a button it would read ‘ button, double tap to activate’ by default, but for our ImageView icon we manually specify the action as we do not have this default.

android:contentDescription="tap to toggle extra person information"

We also use importantForAccessibility:no to turn OFF focus for the ‘+’ TextView, as the text beneath the two badges provides a description and so the ‘+’ is more confusing than helpful if read aloud.

For both of these, manual testing on a real device with TalkBack turned on is the best indication of whether the context makes sense without visuals.

Expand Animation

Our animation will activate on an ‘info’ icon tap, toggling the expanding of a details section.

We will do this all inside a single activity to allow focus simply on the animation code. In a real world app, the view this is applied to is more likely to be within its own fragment or recycler view, so a more abstracted code structure would be used.

Setting a listener

Within our example activity’s onCreate we must first set a listener on our icon and pass in the view that is to be toggled.

infoIcon.setOnClickListener **{** toggleCardBody(root.personEntryBody) **}**

We also set up a variable within the class to track if the view is toggled, setting it to initially be closed.

private var isToggled = false

Toggle expand animation

Within our layout, we have set the height of personEntryBody to 0dp.

To toggle this open we need to know the new height to set it to, how long the animation should be, and what height it should be at each moment of the animation.

We then need to set isToggled to its inverse, and ensure that when tapped again it does the reverse.

**private fun** toggleCardBody(body: View) {
    body.measure(ViewGroup.LayoutParams._MATCH_PARENT_, ViewGroup.LayoutParams._WRAP_CONTENT_)
    **val** maxHeight = body._measuredHeight_ + body._paddingTop_ + body._paddingBottom_ **val** startHeight = **if** (**isToggled**) maxHeight **else** 0
    **val** targetHeight = **if** (**isToggled**) 0 **else** maxHeight
**val** expandAnimator = ValueAnimator
    .ofInt(startHeight, targetHeight)

expandAnimator.addUpdateListener **{
    val** value = **it**._animatedValue_ **as** Int
    body._layoutParams_.**height** = value
**}** expandAnimator._doOnEnd_ **{
 **   isToggled = !isToggled **}** expandAnimator.start()


As the height when the view is initially drawn is 0, we must calculate its new size by remeasuring its layout.

As described in the Android view layout docs, we can use measure() along with the layout params we assigned to the view to remeasure each time the info icon is tapped.

To calculate the max height we must manually add the top and bottom padding to this, as these are not included in the measured height.

Depending on isToggled we then know if we are starting from 0 or starting from the expanded max height, and so the opposing target height.

We use a Value Animator to move from the starting value to the target end value, and set the duration in ms. This duration is based purely on later manual testing for UX feel.

.ofInt(startHeight, targetHeight)

We tie the duration to the height with an update listener, requesting a new layout to be drawn after each update and adjusting the height each time.

    expandAnimator.addUpdateListener {
value = it.animatedValue as Int
body.layoutParams.height = value
} expandAnimator.doOnEnd **{
** isToggled = !isToggled } expandAnimator.start()

As we are using Kotlin, we also add the [androidx]( to our build.gradle to benefit from its doOnEnd extension. This allows us to very easily inverse the isToggled variable.

Finally we start our animation! Already we have a body that expands and contracts on an icon touch!

Smoother animations

While our animation technically works as is, a nice extra step is to add an interpolator so that the movement feels more natural.

expandAnimator.interpolator = FastOutSlowInInterpolator()

Increasing our accessibility

We’ll add two final things to hopefully help our a11y users.

First we can help with navigation using an [AccessibilityEvent]( .

expandAnimator.doOnEnd { if (!isToggled)       body.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_FOCUSED)
isToggled = !isToggled }

This means that when the animation moves from closed to open, the focus will immediately jump to the focus on the first item in the body, in this case the description. In the layout, we set the description of the info icon action, but as we may not be able to rely on a visual indicator for the user to move to the next item we can handle this for them.

Second we allow for different font sizes. The measured height returned from measure() does not account for font scaling set in the devices accessibility settings, and so when at a large scale the bottom of the description will be cropped as it is too large to fit.

We can access the font scale programmatically, and scale our height based on this. We convert it to an integer as the font scale may result in a float which would not work as a layout height.

val a11yFontScale = body.context.resources.configuration.fontScale
maxHeight = ((body.measuredHeight + body.paddingTop + body.paddingBottom) * a11yFontScale).toInt()


And there we have it, we have arrived at our final animation! With just a few extra lines we have greatly increased its a11y coverage and have a smooth expanding section revealing a Kotlin and Android badge 😉

Thanks for reading 😁

Originally published by Dominic Fraser at

Learn more

☞ The Complete Android Kotlin Developer Course

☞ Kotlin for Android: Beginner to Advanced

☞ Kotlin for Beginners: Learn Programming With Kotlin

☞ Android Kotlin Development Masterclass using Android Oreo

☞ Kotlin for Android & Java Developers: Clean Code on Android

☞ Kotlin Android Development Masterclass - With Android Oreo

ECommerce Mobile App Development | Ecommerce Mobile App Development Services

We are leading ecommerce mobile application development company. Hire our ecommerce mobile app developer for your custom Ecommerce project at competitive rates. **Know about [Top ECommerce Mobile App Development...

We are leading ecommerce mobile application development company. Hire our ecommerce mobile app developer for your custom Ecommerce project at competitive rates.

Know about Top ECommerce Mobile App Development Company

Build Native Android Apps with Kotlin

Build Native Android Apps with Kotlin

Learn to build native Android apps with Kotlin. You will also learn how to use Android Jetpack, Firebase, Room, MVVM, Navigation, LiveData, and Kotlin Coroutines. This full course explains how to build an entire Android app using best practices.

Learn to build native Android apps with Kotlin. You will also learn how to use Android Jetpack, Firebase, Room, MVVM, Navigation, LiveData, and Kotlin Coroutines. This full course explains how to build an entire Android app using best practices.

⭐️ Course Contents ⭐️

(0:00) Introduction

(5:14) Model View ViewModel (MVVM) Architecture fundamentals and variations
(5:38) Is MVVM the perfect architecture?
(7:41) Overview of MVVM with whiteboard example
(12:11) Pros and Cons of MVVM
(18:58) Package structure

(23:22) How to create Vector Drawables
(24:22) Difference between Raster (PNG, JPG, BMP) and Vector (SVG) Images?
(27:55) Uh Oh!
(28:41) How to use Inkscape to create an SVG from a BMP/PNG
(30:07) How to convert an SVG into an Android Studio Vector Asset
(32:29) How to create simple animations using animation lists and fade animations

(38:19) Material Design User Interface using ConstraintLayout and Styles
(41:00) Building an XML Layout using ConstraintLayout
(51:09) Using ConstraintLayout Chains
(55:43) Some tips on using Styles to create a material design look

(56:51) How to use (and when not to use) the Android Navigation Component from Android Jetpack
(1:00:00) Adding Safe Args to gradle
(1:01:15) Building a Navigation Graph using the Navigation Editor (XML)
(1:11:00) Creating a NavHostFragment to host the Navigation Component and adding it to an Activity
(1:15:29) How to actually change destinations in our Fragments using the Navigation Component (with safe args)

(1:20:00) Setting up Fragments as Views in MVVM using Kotlin Synthetic Properties
(1:25:32) Starting point
(1:27:54) Importing an XML layout to an Activity/Fragment using Kotlin Synthetic Properties
(1:32:09) How to reference Views in the Fragment using synthetic properties
(1:33:41) Adding onClickListener to our views
(1:38:03) Intercepting OnBackPressed (NOTE: The API for this has changed since making this video. I have updated the Repository appropriately)
(1:39:40) How to observe the ViewModel using LiveData callbacks

(1:43:22) ViewModels in MVVM with Kotlin Coroutines for Concurrency
(1:45:26) A look at my BaseViewModel class which contains part of the Coroutines Implementation (Coroutine Scope)
(1:49:25) Starting point
(2:01:40) Handling events from the View in the ViewModel
(2:05:34) Using the launch Coroutine Builder to access data
(2:08:44) How to update the MutableLiveData fields to publish data to the View

(2:19:35) Modern RecyclerView implementation using LiveData to handle ItemTouchListener() callbacks
(2:22:49) Overview of the RecyclerView within the XML View with LinearLayoutManager
(2:26:53) What does the DiffUtil do?
(2:28:48) A look at the source code of ListAdapter to better understand how it works
(2:35:34) Writing the RecyclerView.ViewHolder class
(2:37:23) Why is it actually called a RecyclerView? What gets Recycled?
(2:37:58) Writing our RecyclerView.ListAdapter
(2:46:37) How to use a MutableLiveData object to publish events from the onClickListener in the ViewHolders
(2:48:09) Overview of the Fragment which manages the RecyclerView, and how to avoid memory leaks!

(2:53:17) FirebaseAuth for User Authentication using Google Sign In
(2:54:00) How to set up a new Firebase Project using Android Studio
(2:54:36) Enabling Authentication (FirebaseAuth) in the Firebase Console
(2:55:00) Setting up a debug signing certificate for your App in Firebase
(2:56:48) Gradle Configurations for FirebaseAuth
(2:58:00) Setting up GoogleSignInProvider
(2:59:24) Handling the result in onActivityResult
(3:01:06) Back FirebaseAuth Implementation using Coroutines

(3:05:31) Local Database with Room Persistence Library and Coroutines
(3:06:17) Entities and Primary Keys in Room
(3:08:50) Setting up a Dao (Data Access Object) in Room
(3:12:28) Overview of RoomDatabase implementation
(3:14:21) How to build your Database and get a reference to you Dao
(3:14:47) How to get data in and out of the Dao using suspend functions

(3:16:34) Setting up a Local and Remote Database using Firebase's Firestore NoSQL library
(3:17:33) Communicating with Firestore using a Repository, with Coroutines

(3:21:59) Dependency Injection using an AndroidViewModel, and ViewModelProvider.Factory
(3:22:29) What is dependency injection in simple terms?
(3:23:36) Implementing Dependency Injection using AndroidViewModel
(3:24:13) Quick look at using a ViewModelProvider.Factory to create our ViewModel with the Injected Repository
(3:24:27) How to use our Dependency Injector from within a Fragment or Activity

💻 Code:

Kotlin For Android Developers: Top 7 Android Apps Written In Kotlin You Should Know

Kotlin For Android Developers: Top 7 Android Apps Written In Kotlin You Should Know

Looking for Kotlin for Android Developers? or Want to Develop Android apps with Kotlin?Read the following article about understanding Kotlin & 7 application built with kotlin.

Looking for Kotlin for Android Developers? or Want to Develop Android apps with Kotlin?Read the following article about understanding Kotlin & 7 application built with kotlin.

Writer’s Note: For all the aspiring developers reading this blog you are in for a treat. For the non-nerd entrepreneurs, I won’t bore you with technical jargons; instead I’ll introduce you to Kotlin in the simplest way possible

A Brief History of Kotlin: (How did this beast come to exist?)

In July of 2011, a very smart group of individuals (collectively known as JetBrains) unveiled to the world their prized invention, Kotlin.

Kotlin for Android developers has become a token of excellence ever since. It was only 5 years later that the first official version 1.0 released in 2016. The most recent Kotlin version is 1.3.10 released in November of 2018.

(A Tip For Entrepreneurs: If any company tries to pull a fast one on you just ask them which version they are using currently. Ask a bit technical questions to show them who’s the boss, but do slight research beforehand.)

Kotlin becomes the Primary Choice: (Why Google made Kotlin their Number 1?)

Andrey Breslav (father of Kotlin) said that Kotlin for Android developers is designed to be an industrial-strength object-oriented language, and a “better language” than Java, and they proved it all the way through. Features like Interoperability with Java, Conciseness, and Android Studio support were reasons enough for Google to make the official switch from Java to Kotlin. But they hit jackpot with this new language (also considered as the Swift of Android).

(A Tip For Developers: Great companies and startups like Google, Netflix, Uber, and many others are already using code base of Kotlin. It’s a great time to make the jump and migrate from Java to Kotlin.)

7 Apps Written in Kotlin ( Kotlin Examples )

If you don’t believe me then trust these 7 world-class brands that have built their Mobile app using Kotlin. Here are the famous android apps built using Kotlin:

1. Pinterest

It is by far the most famous photo-sharing social platform. So when Pinterest made the jump from Java to Kotlin in 2016 they set a huge example for other companies. Pinterest showcased the benefits they received from going with Kotlin at the Droidcon NYC 2016. One amazing thing is that Pinterest made the change to Kotlin even before Google announced the first-class support for Kotlin. These facts make Pinterest probably the best kotlin android example on this list.

2. Trello

Atlassian owned project-management application; Trello has been helping many companies and individuals with their working process. As per the recent announcement by Atlassian; Kotlin will be the programming language.. Efficient interoperability between Java and Kotlin was the reason to go with Kotlin. This decision made Trello an overnight favorite on Google Play with an average 4.5 rating from 69,000+ reviews.

3. Coursera

Coursera provides online courses by remarkable universities and institutes such as Stanford and Yale. It’s an educational company providing open online courses that didn’t have separate Android and iOS organizations. They only had the concept of mobile and that’s why they decided to start using Kotlin. It’s similar to Swift hence resulting in easier knowledge sharing between engineers, better communication, and more efficient overall development.

4. Twidere

Twidere is a fully designed Twitter browser that enhances the user experience of the Twitter platform. It is an open source Twitter client app used to customize themes, filter unwanted tweets, manage multiple accounts, and do many other things. Twidere is the perfect combination of Kotlin and Java code. The simplicity and smooth performance of this app have earned it 1600+ stars on Github and 100,000+ downloads from Google Play.

5. Shadowsocks

Shadowsocks is a cross-platform secured SOCKS5 proxy app. The app helps its users to access the internet privately and safely. The app provides an industry-level encryption algorithm and it’s optimized for mobile devices and wireless networks. Shadowsocks is a staggering success with 13,000+ stars Github and an average rating of 4.6 on Google Play Store from 52,000+ reviews.

6. Square

Square, the online payment platform announced their approval to use Kotlin for Android developers internally for their app development projects in 2015. Since then, Square has been in love with Kotlin and what it can do. Many of you must know what a big name Square is in the online payment industry. So their decision of going with Kotlin has set an example for many startups and enterprises.

7. Evernote

Evernote is an advanced version of Trello with a lot more features. With features like organizing, task lists, note-taking, and archiving Evernote decided to integrate Kotlin into their Android client. Kotlin has made the Android app development very easy and flexible. Due to this amazing additional features became possible like input typed notes, scan handwritten notes, images, web pages, add to-do’s, photos, and even audio.

Why you should go for Kotlin Android App Development
    1. Even if you don’t know anything about Kotlin, you can still set up a Kotlin for Android developers Kotlin project without any problem.
    1. Kotlin is faster to write, hence; saving time and resources in creating an Android app.
    1. You can do many things like debug without issues, run from the IDE, and use the instant run among many other things.
    1. Moreover; JetBrains and Google are the two huge companies working on Kotlin to make it a nest for long-term Android development.
    1. Kotlin solved the null point exception trouble by having null right in its type system making the code less prone to errors and more stable.
    1. Kotlin has many new features like continuous library size optimization, various Kotlin Android extensions, and libraries like Anko.
    1. Any device that can run JVM will be able to use Kotlin virtually.
    1. A developer can also use Kotlin for front-end development for any version higher than Kotlin 1.1
    1. With Gradle support, coders can write their Gradle files in Kotlin and with Kotlin native the future is open for any platform.

Kotlin is on the rise and it won’t be stopping any time soon. It is the bright new future of Android app development and if you wish to be part of the future then you better tighten your belt and make a run towards Kotlin. If you wish to make a big name in the Android market, find a reliable development team offering Kotlin app development services for your projects or hire Kotlin developers of top caliber. For the developers who wish to build an Android App in Kotlin, this is the time to join such companies.