
Boost your productivity and write cleaner, more expressive code with Kotlin extensions! These handy shortcuts enhance the language, enabling you to simplify common tasks like network availability checks, toast messages, and soft keyboard handling. Convert units, retrieve screen dimensions, parse colors, start activities effortlessly, and format dates in a snap. Unleash your creativity and code with ease!
fun Context.isNetworkAvailable(): Boolean {
val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val networkInfo = connectivityManager.activeNetworkInfo
return networkInfo?.isConnectedOrConnecting == true
}
// Example usage:
if (context.isNetworkAvailable()) {
// Perform network-related tasks
}
fun Context.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, message, duration).show()
}
// Example usage:
toast("Hello, World!")fun View.isVisible(): Boolean = visibility == View.VISIBLE
// Example usage:
if (textView.isVisible()) {
// View is visible
}
fun Activity.hideKeyboard() {
val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
val currentFocusView = currentFocus
if (currentFocusView != null) {
inputMethodManager.hideSoftInputFromWindow(currentFocusView.windowToken, 0)
}
}fun View.toBitmap(): Bitmap {
val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
draw(canvas)
return bitmap
}
// Example usage:
val bitmap = imageView.toBitmap()
fun Context.dpToPx(dp: Int): Int {
val density = resources.displayMetrics.density
return (dp * density).toInt()
}
// Example usage:
val pixels = context.dpToPx(16)
fun Context.getScreenWidth(): Int {
val displayMetrics = resources.displayMetrics
return displayMetrics.widthPixels
}
fun Context.getScreenHeight(): Int {
val displayMetrics = resources.displayMetrics
return displayMetrics.heightPixels
}
// Example usage:
val screenWidth = context.getScreenWidth()
val screenHeight = context.getScreenHeight()
fun String.parseColor(): Int = Color.parseColor(this) // Example usage: val color = "#FF0000".parseColor()
inline fun <reified T : Activity> Context.startActivity() {
val intent = Intent(this, T::class.java)
startActivity(intent)
}
// Example usage:
startActivity<MainActivity>()
fun Date.toFormattedDateString(pattern: String): String {
val dateFormat = SimpleDateFormat(pattern, Locale.getDefault())
return dateFormat.format(this)
}
// Example usage:
val currentDate = Date()
val formattedDate = currentDate.toFormattedDateString("dd/MM/yyyy")
Every week (ish) I share actionable engineering tips, android and iOS development news, and high-quality insights from across the industry, directly to your inbox.
Covering a wide range of topics including freelancing, Android, iOS, mobile development, wealth, business tips, and entrepreneurship.