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.

Layout

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)
    .setDuration(200)

expandAnimator.addUpdateListener **{
    val** value = **it**._animatedValue_ **as** Int
    body._layoutParams_.**height** = value
    body.requestLayout()
**}** 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.

ValueAnimator
.ofInt(startHeight, targetHeight)
.setDuration(200)

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 {
val
value = it.animatedValue as Int
body.layoutParams.height = value
body.requestLayout()
} expandAnimator.doOnEnd **{
** isToggled = !isToggled } expandAnimator.start()

As we are using Kotlin, we also add the [androidx](https://developer.android.com/kotlin/ktx#core-packages)library 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](https://developer.android.com/reference/android/view/accessibility/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
val
maxHeight = ((body.measuredHeight + body.paddingTop + body.paddingBottom) * a11yFontScale).toInt()

Finished!

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 https://medium.freecodecamp.org

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

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 ⭐️

1
(0:00) Introduction

2
(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

3
(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

4
(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

5
(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)

6
(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

7
(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

8
(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!

9
(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

10
(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

11
(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

12
(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: https://github.com/BracketCove/SpaceNotes

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.

Originally published by Mayur Panchal at  excellentwebworld.com

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.

  • 2. Kotlin is faster to write, hence; saving time and resources in creating an Android app.

  • 3. You can do many things like debug without issues, run from the IDE, and use the instant run among many other things.

  • 4. Moreover; JetBrains and Google are the two huge companies working on Kotlin to make it a nest for long-term Android development.

  • 5. 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.

  • 6. Kotlin has many new features like continuous library size optimization, various Kotlin Android extensions, and libraries like Anko.

  • 7. Any device that can run JVM will be able to use Kotlin virtually.

  • 8. A developer can also use Kotlin for front-end development for any version higher than Kotlin 1.1

  • 9. With Gradle support, coders can write their Gradle files in Kotlin and with Kotlin native the future is open for any platform.


Conclusion

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.

Originally published by Mayur Panchal at  excellentwebworld.com

=============================================

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter

Learn More

☞ The Complete Android Kotlin Developer Course

☞ Kotlin for Android O Development: From Beginner to Advanced

☞ Kotlin for Beginners: Learn Programming With Kotlin

☞ Kotlin for Android: Beginner to Advanced

☞ Kotlin for Java Developers

☞ The Kotlin Language: Fundamentals and Basics

☞ Android App Development Masterclass using Kotlin


Top 5 Kotlin Features That Every Android App Developer Must Know

Top 5 Kotlin Features That Every Android App Developer Must Know

Here are the top five features that every Android developer must know about Kotlin.

Here are the top five features that every Android developer must know about Kotlin.

Java is considered to be the heart of the Android operating system, and so, for every Android developer, there is hardly any alternative than Java. Well, at last, a superb alternative to Java has appeared with a lot of value packed within. Kotlin is a programming language that comes as a better and more effective alternative to Java for Android development.

At this moment even, the Android community is abuzz with the discussion on Kotlin. This is precisely why we are going to explain the five key features of Kotlin.

Kotlin Advantages Over Java

Kotlin, being designed and developed by JetBrains, has arrived to address a whole array of shortcomings of Java. While Java will not fade away into the thin air so soon, Kotlin will continue to dominate the Android development space in the time to come.

Let us have a look at the key areas where Kotlin offers a lot more than Java.

  • Kotlin comes with an array of tools and frameworks that work with Java.
  • Kotlin, as a programming language, is more clear and concise than Java.
  • Kotlin compared to Java helps reduce code and helps minimize errors.
  • Kotlin, unlike Java, comes loaded with an advanced compiler that can check errors at compile time and runtime.

1. Efficiency

Kotlin is a programming language with a really low learning curve. Moreover, it helps a developer building an application with a minimum volume of code. In terms of both learning and grasping the language and coding an app, Kotlin helps to do things faster.

It reduced the length of the code lines to a minimum. With the code length being at least one-fifth less compared to Java, Kotlin offers far better chances of producing higher quality applications.

2. Null Safety in Kotlin

The null safety feature is one of the key beneficial aspects of Kotlin that every Android developer will find helpful. While coding with the Java programming language, every Java developer has to deal with the NullPointerException a lot of times. While this particular element helps to test the software quality, it actually pulls down the development speed and efficiency to a great extent.

The prevention implemented by this makes things complicated in the run-time of the application, and developers always like to do away with this when compiling the code. In the case of Java, no information on the null-safety is provided at all.

This is exactly where this Kotlin feature can bring a lot of benefits. Kotlin brings the null safety feature for Java developers only at the early stage during initiation. At this point in time, whether the values can be assigned to the null factor or not is mentioned to the developer. With Kotlin, the compiler provides the null safety that brings down the risk of facing run-time Null Point Exceptions for the developers.

3. Lazy-Loading Feature

Faster loading speed is one of the most crucial criteria for any quality app now. The lazy loading feature offered by Kotlin actually takes care of this. When you use Kotlin for Android development, this feature will help you minimize the startup time for the app. This feature actually loads the initial content faster to reduce startup time while slowly loading other less necessary elements and contents down the page.

Thanks to this lazy-loading feature, the Android developers working with Kotlin can just give priority to the primary resources and keep them in main memory to ensure faster loading while keeping others or secondary resources in secondary memories.

4. Extension Functions

The extension functions, which are also called the Standard Library Functions by Kotlin developers, is a key feature that can help developers in many ways. While programming with Kotlin, functions that are basic parts of an object-oriented language can be rendered as extensions as well.

While Java only allows developers to incorporate a new function within a prevailing class, the class that is further expanding can be problematic for developers to access ready-to-use parts. In contrast, Kotlin allows us to use these functions as extensions. This helps to add new functions smoothly to the existing classes. This extension function feature apart, the Standard Library of Kotlin also provides a robust choice of standard functions.

5. Collections and Streams

If you are a Java developer, you must have an idea of processing object collection that always make an irreplaceable part of the Java app development process. This happens because Java objects get translated to a variety of presented elements through this process. This often causes a parallel stream of translated objects, resulting in the slowing down of the entire application.

Kotlin, as an advanced programming language, tackles this with immutable collections. Here, rich functional APIs will automatically return as the collections are characterized by the identical functionality.

Conclusion

In spite of so many advanced features and advantages over Java, Kotlin can be used by Android developers alongside Java as well. This interoperability with Java and low learning curve has made Kotlin an unbeatable choice for Android developers.