How to Create Custom Loading Button By Extending ViewClass in Android?
In this article, we are going to create a custom loading button by extending the View class and animate properties of the custom button once it’s clicked. We had come across many times while downloading any file and keeping our eyes on the downloading progress. Here we will only create that custom button with animation. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Create a Sealed class, ButtonState which describes the state (like clicked, loading & completed) of the custom button. Below is the code for the ButtonState.kt file.
Step 3: Create another class, LoadingButton in which everything related to the button like color, text, animation, etc will be defined. Make a constructor by annotating it with JvmOverloads. Below is the code for the LoadingButton.kt file.
Step 4: Working with the XML file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
attrs.xml (under res -> values )
loading_animation.xml (under res -> animator, create animator directory under res)
Step 5: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Source Code: Link