Skip to content

Instantly share code, notes, and snippets.

@delacrixmorgan
Last active November 28, 2020 12:49
Show Gist options
  • Save delacrixmorgan/951cea75393b29331fd7f7ee44af071b to your computer and use it in GitHub Desktop.
Save delacrixmorgan/951cea75393b29331fd7f7ee44af071b to your computer and use it in GitHub Desktop.
Kotlin Util Extensions

Kotlin Util Extensions

View

ViewExtensions.kt

fun Fragment.showKeyboard() {
    view?.showKeyboard()
}

fun Fragment.hideKeyboard() {
    view?.hideKeyboard()
}

fun View.showKeyboard() {
    val inputMethodManager = context.getSystemService(
        Activity.INPUT_METHOD_SERVICE
    ) as InputMethodManager

    inputMethodManager.toggleSoftInput(
        InputMethodManager.SHOW_FORCED,
        InputMethodManager.HIDE_IMPLICIT_ONLY
    )
}

fun View.hideKeyboard() {
    val inputMethodManager = context.getSystemService(
        Activity.INPUT_METHOD_SERVICE
    ) as InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
}

Context

ContextExtensions.kt

fun Context.getQuantityStringZero(
    quantity: Int,
    pluralResId: Int,
    zeroResId: Int? = null
): String {
    return if (zeroResId != null && quantity == 0) {
        resources.getString(zeroResId)
    } else {
        resources.getQuantityString(pluralResId, quantity, quantity)
    }
}

val Context.isNetworkAvailable: Boolean
    get() {
        val connectivityManager = getSystemService(
            Context.CONNECTIVITY_SERVICE
        ) as ConnectivityManager

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val network = connectivityManager.activeNetwork ?: return false
            val networkCapabilities = connectivityManager.getNetworkCapabilities(
                network
            ) ?: return false

            return networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) || networkCapabilities.hasTransport(
                NetworkCapabilities.TRANSPORT_CELLULAR
            )
        } else {
            return connectivityManager.activeNetworkInfo?.isConnected == true
        }
    }

Date

DateExtensions.kt

fun Date.withTime(hour: Int, minute: Int, second: Int): Date {
    val calendar = Calendar.getInstance()
    calendar.time = this

    calendar.set(Calendar.HOUR_OF_DAY, hour)
    calendar.set(Calendar.MINUTE, minute)
    calendar.set(Calendar.SECOND, second)
    calendar.set(Calendar.MILLISECOND, 0)

    return calendar.time
}

fun Date.startOfDay(): Date {
    return this.withTime(hour = 0, minute = 0, second = 0)
}

fun Date.isToday(): Boolean {
    val today = Date().startOfDay()
    return this.startOfDay().time == today.time
}

fun Date.daysSince(anotherDate: Date): Int {
    return (((this.startOfDay().time - anotherDate.startOfDay().time) / 1000) / 86400).toInt()
}

fun Date.stringWithFormat(format: String, locale: Locale = Locale.getDefault()): String {
    val dateFormat = SimpleDateFormat(format, locale)
    return dateFormat.format(this)
}

fun Date.UTCStringWithFormat(format: String, locale: Locale = Locale.getDefault()): String {
    val dateFormat = SimpleDateFormat(format, locale)
    dateFormat.timeZone = TimeZone.getTimeZone("UTC")
    return dateFormat.format(this)
}

String

StringExtensions.kt

fun String.toDate(
        format: String,
        timeZone: TimeZone = TimeZone.getDefault(),
        locale: Locale = Locale.getDefault()
): Date? {
    val dateFormat = SimpleDateFormat(format, locale)
    dateFormat.timeZone = timeZone

    return try {
        dateFormat.parse(this)
    } catch (e: ParseException) {
        null
    }
}

fun String.toUTCDate(format: String): Date? {
    return toDate(
            format = format,
            timeZone = TimeZone.getTimeZone("UTC"),
            locale = Locale.US
    )
}

fun String.isEmail(): Boolean {
    return if (this.length < 5) {
        false
    } else !this.isEmpty() && this.matches("[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}".toRegex())
}

fun String.isPhone(): Boolean {
    return !this.isEmpty() && this.matches("^[+]?\\d{7,}$".toRegex())
}

fun String.isAlphanumeric(): Boolean {
    return this.replace(Regex("[a-zA-Z0-9]"), "").isEmpty()
}

fun String.fromHtml(): String {
    try {
        return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            Html.fromHtml(this, Html.FROM_HTML_MODE_LEGACY).toString()
        } else {
            Html.fromHtml(this).toString()
        }
    } catch (e: NullPointerException) {
        return ""
    }
}

fun String.nameInitials(): String {
    val components = this.split(" ")

    val initialsBuffer = StringBuffer()
    for (component in components) {
        val cleanComponent = component.replace("\\W".toRegex(), "")
        if (cleanComponent.isEmpty()) {
            continue
        }
        initialsBuffer.append(cleanComponent.firstOrNull() ?: "")
    }

    if (initialsBuffer.length > 2) {
        initialsBuffer.delete(1, initialsBuffer.length - 1);
    }
    return initialsBuffer.toString().toUpperCase();
}

fun String.extractAlphanumerics(): String {
    return this.replace("[^a-zA-Z0-9]".toRegex(), "")
}

fun Editable.extractAlphanumerics(): Editable {
    val alphanumericString = this.replace("[^a-zA-Z0-9]".toRegex(), "")
    return Editable.Factory.getInstance().newEditable(alphanumericString)
}

fun String.extractDigits(): String {
    return this.replace("\\D".toRegex(), "")
}

fun Editable.extractDigits(): Editable {
    val digitsOnly = this.toString().replace("\\D".toRegex(), "")
    return Editable.Factory.getInstance().newEditable(digitsOnly)
}

fun String.substringRange(substring: String, startIndex: Int = 0, ignoreCase: Boolean = false): StringUtils.Range {
    val startIndex = this.indexOf(substring, startIndex, ignoreCase)
    return StringUtils.Range(startIndex, substring.length)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment