|
1 | 1 | # Kotlin.someExtensions
|
2 | 2 | Few extensions functions for Kotlin and Android
|
3 | 3 |
|
4 |
| -File names represent their content. |
| 4 | +# ImageExtensions.kt |
| 5 | + ```kotlin |
| 6 | + /** |
| 7 | + * Convert byte array to bitmap |
| 8 | + */ |
| 9 | +fun ByteArray.convertBytesToBitmap(): Bitmap = |
| 10 | + BitmapFactory.decodeByteArray(this, 0, size) |
| 11 | + |
| 12 | +/** |
| 13 | + * Convert bitmap to a byte array |
| 14 | + */ |
| 15 | +fun Bitmap.convertBitmapToBytes(): ByteArray { |
| 16 | + val bytes: ByteArray |
| 17 | + val stream = ByteArrayOutputStream() |
| 18 | + this.compress(Bitmap.CompressFormat.PNG, 0, stream) |
| 19 | + bytes = stream.toByteArray() |
| 20 | + return bytes |
| 21 | +} |
| 22 | + ``` |
| 23 | +# ContextExtensions.kt |
| 24 | + ```kotlin |
| 25 | + /** |
| 26 | + * Checks network connectivity |
| 27 | + */ |
| 28 | +@RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE) |
| 29 | +fun Context.isNetworkStatusAvailable(): Boolean { |
| 30 | + val connectivityManager = this |
| 31 | + .getSystemService(Context.CONNECTIVITY_SERVICE) as? ConnectivityManager |
| 32 | + connectivityManager?.let { |
| 33 | + val netInfo = it.activeNetworkInfo |
| 34 | + netInfo?.let { |
| 35 | + if (netInfo.isConnected) return true |
| 36 | + } |
| 37 | + } |
| 38 | + return false |
| 39 | +} |
| 40 | + |
| 41 | +/** |
| 42 | + * Execute block of code if network is available |
| 43 | + */ |
| 44 | +@RequiresPermission(Manifest.permission.ACCESS_NETWORK_STATE) |
| 45 | +inline fun Context.withNetwork(block: () -> Unit) { |
| 46 | + if (isNetworkStatusAvailable()) { |
| 47 | + block() |
| 48 | + } |
| 49 | +} |
| 50 | + |
| 51 | +/** |
| 52 | + * Loads content of file from assets as String using UTF-8 charset |
| 53 | + */ |
| 54 | +fun Context.loadFromAsset(jsonName: String): String? { |
| 55 | + var stream: String? = null |
| 56 | + try { |
| 57 | + val inputStream = this.assets.open(jsonName) |
| 58 | + val size = inputStream.available() |
| 59 | + val buffer = ByteArray(size) |
| 60 | + inputStream.read(buffer) |
| 61 | + inputStream.close() |
| 62 | + stream = String(buffer, Charset.forName("UTF-8")) |
| 63 | + } catch (e: IOException) { |
| 64 | + } |
| 65 | + return stream |
| 66 | +} |
| 67 | + |
| 68 | +/** |
| 69 | + * Computes status bar height |
| 70 | + */ |
| 71 | +fun Context.getStatusBarHeight(): Int { |
| 72 | + var result = 0 |
| 73 | + val resourceId = this.resources.getIdentifier("status_bar_height", "dimen", |
| 74 | + "android") |
| 75 | + if (resourceId > 0) { |
| 76 | + result = this.resources.getDimensionPixelSize(resourceId) |
| 77 | + } |
| 78 | + return result |
| 79 | +} |
| 80 | + |
| 81 | +/** |
| 82 | + * Computes screen height |
| 83 | + */ |
| 84 | +fun Context.getScreenHeight(): Int { |
| 85 | + var screenHeight = 0 |
| 86 | + val wm = this.getSystemService(Context.WINDOW_SERVICE) as? WindowManager |
| 87 | + wm?.let { |
| 88 | + val metrics = DisplayMetrics() |
| 89 | + wm.defaultDisplay.getMetrics(metrics) |
| 90 | + screenHeight = metrics.heightPixels |
| 91 | + } |
| 92 | + return screenHeight |
| 93 | +} |
| 94 | + |
| 95 | +/** |
| 96 | + * Convert dp integer to pixel |
| 97 | + */ |
| 98 | +fun Context.dpToPx(dp : Int): Float { |
| 99 | + val displayMetrics = this.resources.displayMetrics |
| 100 | + return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT)).toFloat() |
| 101 | +} |
| 102 | + |
| 103 | +/** |
| 104 | + * Get color from resources |
| 105 | + */ |
| 106 | +fun Context.getCompatColor(@ColorRes colorInt: Int) : Int = |
| 107 | + ContextCompat.getColor(this, colorInt) |
| 108 | + |
| 109 | +/** |
| 110 | + * Get drawable from resources |
| 111 | + */ |
| 112 | +fun Context.getCompatDrawable(@DrawableRes drawableRes: Int) : Drawable = |
| 113 | + ContextCompat.getDrawable(this, drawableRes) |
| 114 | + ``` |
| 115 | +# ActivityExtensions.kt |
| 116 | + ```kotlin |
| 117 | + /** |
| 118 | + * AppCompatActivity's toolbar visibility modifiers |
| 119 | + */ |
5 | 120 |
|
6 |
| -//TODO - Do something for more documentation. |
| 121 | +fun AppCompatActivity.hideToolbar() { |
| 122 | + supportActionBar?.hide() |
| 123 | +} |
| 124 | + |
| 125 | +/** |
| 126 | + * Returns display density as ...DPI |
| 127 | + */ |
| 128 | +fun AppCompatActivity.getDisplayDensity(): String { |
| 129 | + val metrics = DisplayMetrics() |
| 130 | + this.windowManager.defaultDisplay.getMetrics(metrics) |
| 131 | + return when (metrics.densityDpi) { |
| 132 | + DisplayMetrics.DENSITY_LOW -> "LDPI" |
| 133 | + DisplayMetrics.DENSITY_MEDIUM -> "MDPI" |
| 134 | + DisplayMetrics.DENSITY_HIGH -> "HDPI" |
| 135 | + DisplayMetrics.DENSITY_XHIGH -> "XHDPI" |
| 136 | + DisplayMetrics.DENSITY_XXHIGH -> "XXHDPI" |
| 137 | + DisplayMetrics.DENSITY_XXXHIGH -> "XXXHDPI" |
| 138 | + else -> "XXHDPI" |
| 139 | + } |
| 140 | +} |
| 141 | + |
| 142 | +/** |
| 143 | + * Sets color to toolbar in AppCompatActivity |
| 144 | + */ |
| 145 | +fun AppCompatActivity.setToolbarColor(@ColorRes color: Int) { |
| 146 | + this.supportActionBar?.setBackgroundDrawable(ColorDrawable(ContextCompat.getColor(this, |
| 147 | + color))) |
| 148 | +} |
| 149 | + |
| 150 | +/** |
| 151 | + * Perform replace for a support fragment |
| 152 | + */ |
| 153 | +inline fun AppCompatActivity.transact(action: FragmentTransaction.() -> Unit) { |
| 154 | + supportFragmentManager.beginTransaction().apply { |
| 155 | + action() |
| 156 | + }.commit() |
| 157 | +} |
| 158 | + ``` |
| 159 | +# ThreadingBlocks.kt |
| 160 | + ```kotlin |
| 161 | + /** |
| 162 | + * Executes block of code on Android's main thread. Can be called from background thread. |
| 163 | + */ |
| 164 | +inline fun uiThreadExecutor(crossinline block: () -> Unit) { |
| 165 | + val mainHandler = Handler(Looper.getMainLooper()) |
| 166 | + mainHandler.post{ |
| 167 | + block() |
| 168 | + } |
| 169 | +} |
| 170 | + |
| 171 | +/** |
| 172 | + * Executes a function using RxJava observable on a separate thread and |
| 173 | + * exposes it's response as lambda on main thread |
| 174 | + * REQUIRED: RxJava, RxKotlin, RxAndroid |
| 175 | + */ |
| 176 | +fun <T> asyncRxExecutor(heavyFunction: () -> T, response : (response : T?) -> Unit) { |
| 177 | + val observable = Single.create<T>({e -> |
| 178 | + e.onSuccess(heavyFunction()) |
| 179 | + }) |
| 180 | + observable.subscribeOn(Schedulers.newThread()) |
| 181 | + .observeOn(AndroidSchedulers.mainThread()) |
| 182 | + .subscribe { t: T? -> |
| 183 | + response(t) |
| 184 | + } |
| 185 | +} |
| 186 | + |
| 187 | +/** |
| 188 | + * Executes a function using Kotlin coroutines on a separate thread pool and |
| 189 | + * exposes it's response as lambda on main thread. |
| 190 | + * Thread pool is maintained by Anko Coroutines lib |
| 191 | + * REQUIRED: Anko Coroutines |
| 192 | + */ |
| 193 | +fun <T> asyncCoroutinesExecutor(heavyFunction: () -> T, response : (response : T?) -> Unit) { |
| 194 | + async(UI) { |
| 195 | + val data : Deferred<T> = bg { |
| 196 | + heavyFunction() |
| 197 | + } |
| 198 | + response(data.await()) |
| 199 | + } |
| 200 | +} |
| 201 | + ``` |
| 202 | +# GeneralExtensions.kt |
| 203 | + ```kotlin |
| 204 | + /** |
| 205 | + * Wrapping try/catch to ignore catch block |
| 206 | + */ |
| 207 | +inline fun <T> justTry(block: () -> T) = try { block() } catch (e: Throwable) {} |
| 208 | + |
| 209 | +/** |
| 210 | + * App's debug mode |
| 211 | + */ |
| 212 | +inline fun debugMode(block : () -> Unit) { |
| 213 | + if (BuildConfig.DEBUG) { |
| 214 | + block() |
| 215 | + } |
| 216 | +} |
| 217 | + |
| 218 | +/** |
| 219 | + * For functionality supported above API 21 (Eg. Material design stuff) |
| 220 | + */ |
| 221 | +inline fun lollipopAndAbove(block : () -> Unit) { |
| 222 | + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { |
| 223 | + block() |
| 224 | + } |
| 225 | +} |
| 226 | + ``` |
| 227 | +# ViewExtensions.kt |
| 228 | + ```kotlin |
| 229 | + /** |
| 230 | + * Visibility modifiers and check functions |
| 231 | + */ |
| 232 | + |
| 233 | +fun View.isVisibile(): Boolean = this.visibility == View.VISIBLE |
| 234 | + |
| 235 | +/** |
| 236 | + * Sets text and content description using same string |
| 237 | + */ |
| 238 | +fun TextView.setTextWithContentDescription(value : String?) { |
| 239 | + text = value |
| 240 | + contentDescription = value |
| 241 | +} |
| 242 | + |
| 243 | +/** |
| 244 | + * Button enabling/disabling modifiers |
| 245 | + */ |
| 246 | + |
| 247 | +fun Button.disableButton() { |
| 248 | + isEnabled = false |
| 249 | + alpha = 0.3f |
| 250 | +} |
| 251 | + |
| 252 | +/** |
| 253 | + * Sets color to status bar |
| 254 | + */ |
| 255 | +fun Window.addStatusBarColor(@ColorRes color: Int) { |
| 256 | + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { |
| 257 | + this.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS) |
| 258 | + this.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS) |
| 259 | + this.statusBarColor = ContextCompat.getColor(this.context, color) |
| 260 | + } |
| 261 | +} |
| 262 | + ``` |
| 263 | +# StringExtensions.kt |
| 264 | + ```kotlin |
| 265 | + /** |
| 266 | + * Converts string to integer safely otherwise returns zero |
| 267 | + */ |
| 268 | +fun String.toIntOrZero() : Int { |
| 269 | + var value = 0 |
| 270 | + justTry { |
| 271 | + value = this.toInt() |
| 272 | + } |
| 273 | + return value |
| 274 | +} |
| 275 | + |
| 276 | +/** |
| 277 | + * Converts a string to boolean such as 'Y', 'yes', 'TRUE' |
| 278 | + */ |
| 279 | + |
| 280 | +fun String.toBoolean(): Boolean { |
| 281 | + return this != "" && |
| 282 | + (this.equals("TRUE", ignoreCase = true) |
| 283 | + || this.equals("Y", ignoreCase = true) |
| 284 | + || this.equals("YES", ignoreCase = true)) |
| 285 | +} |
| 286 | + |
| 287 | +/** |
| 288 | + * Converts string to camel case. Handles multiple strings and empty strings |
| 289 | + */ |
| 290 | +fun String.convertToCamelCase(): String { |
| 291 | + var titleText = "" |
| 292 | + if (!this.isEmpty()) { |
| 293 | + val words = this.split(" ".toRegex()).dropLastWhile { it.isEmpty() }.toTypedArray() |
| 294 | + words.filterNot { it.isEmpty() } |
| 295 | + .map { it.substring(0, 1).toUpperCase() + it.substring(1).toLowerCase() } |
| 296 | + .forEach { titleText += it + " " } |
| 297 | + } |
| 298 | + return titleText.trim { it <= ' ' } |
| 299 | +} |
| 300 | + ``` |
| 301 | +# MetricExtensions.kt |
| 302 | + ```kotlin |
| 303 | + /** |
| 304 | + * Convert Celsius temperature to Fahrenheit |
| 305 | + */ |
| 306 | +fun Double.celsiusToFahrenheit() : Double = (this * 1.8) + 32 |
| 307 | + |
| 308 | +/** |
| 309 | + * Convert Fahrenheit temperature to Celsius |
| 310 | + */ |
| 311 | +fun Double.fahrenheitToCelsius() : Double = (this - 32) * 5/9 |
| 312 | + |
| 313 | +/** |
| 314 | + * Convert meters to miles |
| 315 | + */ |
| 316 | +fun Double.convertMetersToMiles(): Double { |
| 317 | + return if (this != 0.0) { |
| 318 | + this / 1609.34 |
| 319 | + } else -1.0 |
| 320 | +} |
| 321 | + ``` |
| 322 | +# Drawable.kt |
| 323 | + ```kotlin |
| 324 | + /** |
| 325 | + * Returns a compat drawable with tint added |
| 326 | + */ |
| 327 | +fun Drawable.withTint(colorInt: Int): Drawable { |
| 328 | + return with(this) { |
| 329 | + DrawableCompat.wrap(this).apply { |
| 330 | + DrawableCompat.setTint(this, colorInt) |
| 331 | + } |
| 332 | + } |
| 333 | +} |
| 334 | + ``` |
| 335 | +# DateExtensions.kt |
| 336 | + ```kotlin |
| 337 | + /** |
| 338 | + * Convert a given date to milliseconds |
| 339 | + */ |
| 340 | +fun Date.toMillis() : Long { |
| 341 | + val calendar = Calendar.getInstance() |
| 342 | + calendar.time = this |
| 343 | + return calendar.timeInMillis |
| 344 | +} |
| 345 | + |
| 346 | +/** |
| 347 | + * Checks if dates are same |
| 348 | + */ |
| 349 | +fun Date.isSame(to : Date) : Boolean { |
| 350 | + val sdf = SimpleDateFormat("yyyMMdd", Locale.getDefault()) |
| 351 | + return sdf.format(this) == sdf.format(to) |
| 352 | +} |
| 353 | + |
| 354 | +/** |
| 355 | + * Converts raw string to date object using [SimpleDateFormat] |
| 356 | + */ |
| 357 | +fun String.convertStringToDate(simpleDateFormatPattern: String): Date? { |
| 358 | + val simpleDateFormat = SimpleDateFormat(simpleDateFormatPattern, Locale.getDefault()) |
| 359 | + var value: Date? = null |
| 360 | + justTry { |
| 361 | + value = simpleDateFormat.parse(this) |
| 362 | + } |
| 363 | + return value |
| 364 | +} |
| 365 | + ``` |
0 commit comments