Thanks for showing your love for the Kotlin extension functions in the first part. I would like to share more extensions to help you improve your programming experience with Android and Kotlin. If you have not read it yet, you can check it out at the link below.
10 Useful Kotlin Extension Functions for Android Developer
Improve android development experience using extension function
medium.com
Prerequisite
Should have basic knowledge of kotlin syntax and android
Start working with new chapter…
Value from EditText
Through the text property of EditText, you can quickly obtain the text from EditText. But, it’s Editable. So, we have to convert it to a string for each and every time to get the exact value from EditText. But, here is the catch, you can easily get value from EditText using the extension property listed below.
Usage
val name = etName.value
Start Activity
Start Activity is a common way to transition to another activity. You must first address the intent of the target activity. However, by using this extension function, you can eliminate the intent creation part.
You can also able to customize the intent to pass some data and other things. It’s also able to kill the current calling activity if you want. Look at the examples below.
Usage
startActivity(MainActivity::class.java) // Without Intent modification
startActivity(MainActivity::class.java) {
// You can access the intent object in this block
putExtra("key", "value")
}
Check Network
Nowadays, all our applications have internet connectivity as per our requirements, features, and functionality. So, you may have to check whether an internet connection is available or not.
So, this extension function is useful for checking the internet connection in activity and fragment. It is simple to utilize in the if statement and other locations inside the scope.
Usage
if (isNetworkAvailable()) {
// Called when network is available
} else {
// Called when network not available
}
Check Permission
To fulfill our use cases, you might occasionally have to play with any permission. So, we may have to verify whether the permission is granted or not for our application. Therefore, the extension function below is useful for determining whether or not permission has been given.
Usage
if (isPermissionGranted(Manifest.permission.ACCESS_FINE_LOCATION)) {
// Block runs if permission is granted
} else {
// Ask for permission
}
Remove whitespaces
Sometimes we may have unrealistic text data from Rest API or some other data source. So, if you have more than one whitespace and you want to remove it then we can use removeDuplicateWhitespaces() or if you want to completely remove it then you can use removeAllWhitespaces()extension functions.