Skip to content

Instantly share code, notes, and snippets.

@adavis
Last active April 2, 2024 20:51
Show Gist options
  • Save adavis/8d666aa48dba524415b707296b1329ed to your computer and use it in GitHub Desktop.
Save adavis/8d666aa48dba524415b707296b1329ed to your computer and use it in GitHub Desktop.
Common Android Extensions in Kotlin
fun View.visible() {
visibility = View.VISIBLE
}
fun View.invisible() {
visibility = View.INVISIBLE
}
fun View.gone() {
visibility = View.GONE
}
fun Context.inflate(res: Int, parent: ViewGroup? = null) : View {
return LayoutInflater.from(this).inflate(res, parent, false)
}
inline fun Dialog.ifIsShowing(body: Dialog.() -> Unit) {
if (isShowing) {
body()
}
}
inline fun Snackbar.ifIsShowing(body: Snackbar.() -> Unit) {
if (isShown) {
body()
}
}
inline fun ViewGroup.forEach(action: (View) -> Unit) {
for (index in 0 until childCount) {
action(getChildAtIndex(index))
}
}
operator fun ViewGroup.get(position: Int): View? = getChildAt(position)
@bluemix
Copy link

bluemix commented Jun 6, 2017

fun Activity.showOnUiThread(init: Activity.() -> Unit): Activity {
  if (!isFinishing) {
    runOnUiThread {
      init()
    }
  }

  return this
}

@AdamMc331
Copy link

AdamMc331 commented Jun 6, 2017

fun Boolean.asInt(): Int {
   return if (this) 1 else 0
}

fun Int.asBoolean(): Boolean {
   return (this == 1)
}

I use these for parcelables and also sqlite where booleans are stored as ints.

@ghatasheh
Copy link

inline fun <reified T : Any> mock(): T = Mockito.mock(T::class.java)
// val myObject = mock()

fun <T> on(method: T): OngoingStubbing<T> {
return Mockito.when(method)
}
//on(..).thenReturn(..)

fun ImageView.load(url: String?) {
if (TextUtils.isEmpty(url)) {
Picasso.with(context)
.load(R.mipmap.ic_launcher)
.into(this)
} else {
Picasso.with(context)
.load(url)
.into(this)
}
}

@voghDev
Copy link

voghDev commented Jun 7, 2017

Very useful ones. I'll share some others that I use in my day-by-day

fun Activity.screenWidth(): Int {
    val metrics: DisplayMetrics = DisplayMetrics()
    windowManager.defaultDisplay.getMetrics(metrics)
    return metrics.widthPixels
}

fun Activity.screenHeight(): Int {
    val metrics: DisplayMetrics = DisplayMetrics()
    windowManager.defaultDisplay.getMetrics(metrics)
    return metrics.heightPixels
}

fun Activity.color(resId: Int) : Int {
    return ContextCompat.getColor(this, resId)
}

@adavis
Copy link
Author

adavis commented Jun 8, 2017

These are awesome, thanks for sharing!

@gonzalonm
Copy link

Adding more useful functions

val EMAIL_PATTERN = "^[a-zA-Z0-9#_~!$&'()*+,;=:.\"(),:;<>@\\[\\]\\\\]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*$"

// used for validate if the current String is an email
fun String.isValidEmail(): Boolean {
    val pattern = Pattern.compile(EMAIL_PATTERN)
    return pattern.matcher(this).matches()
}

// used for show a toast message in the UI Thread
fun Activity.toast(message: String) {
    runOnUiThread { Toast.makeText(this, message, Toast.LENGTH_SHORT).show() }
}

// used for simple start activity without Intent parameters
fun Activity.callTo(clazz: Class<out Activity>) {
    startActivity(Intent(this, clazz))
}

@moizest89
Copy link

moizest89 commented Aug 23, 2018

// Transform simple object to String with Gson
 fun <reified T : Any> T.toPrettyJson() : String =  Gson().toJson(this, T::class.java)

// Transform String Json to Object 
inline fun <reified T : Any> String.fromPrettyJson() : T =  Gson().fromJson(this ,  T::class.java)

// Transform String List Json to Object 
inline fun <reified T : Any> String.fromPrettyJsonList() : MutableList <T> =  when( this.isNotEmpty()){
        true -> Gson().fromJson(this, object : TypeToken<MutableList<T>>() {}.type)
        false -> mutableListOf()
}

Copy link

ghost commented Oct 29, 2018

@oscargrgm
Copy link

I don't know if this is very common but it was very useful to me:

private enum class HashType {
    MD5, SHA1, SHA256
}

fun String.applyMD5(): String = this.hashWithAlgorithm(HashType.MD5)

fun String.applySHA1(): String = this.hashWithAlgorithm(HashType.SHA1)

fun String.applySHA256(): String = this.hashWithAlgorithm(HashType.SHA256)

private fun String.hashWithAlgorithm(type: HashType): String {
    return MessageDigest.getInstance(type.name)
        .digest(this.toByteArray(Charsets.UTF_8))
        .joinToString(separator = "") { String.format("%02x", it) }
}

@grndvl1
Copy link

grndvl1 commented Jan 14, 2019

For Preferences and

fun SharedPreferences.edit(func: SharedPreferences.Editor.() -> Unit) {
    val editor = edit()
    editor.func()
    editor.apply()
}

For Context

/**
 * Use this to dismiss keyboards, can always wrap if you needed something else after dismissing
 */
fun Context.dismissKeyboard(view: View?) {
    view?.let{
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(it.getWindowToken(), 0)
    }
}

@imranhsn
Copy link

For dp to px and vice-versa

val Int.dp: Int get() = (this / Resources.getSystem().displayMetrics.density).toInt()

val Int.px: Int get() = (this * Resources.getSystem().displayMetrics.density).toInt()

@shalva97
Copy link

fun OkHttpClient.Builder.ignoreAllSSLErrors(): OkHttpClient.Builder {
    val naiveTrustManager = object : X509TrustManager {
        override fun getAcceptedIssuers(): Array<X509Certificate> = arrayOf()
        override fun checkClientTrusted(certs: Array<X509Certificate>, authType: String) = Unit
        override fun checkServerTrusted(certs: Array<X509Certificate>, authType: String) = Unit
    }

    val insecureSocketFactory = SSLContext.getInstance("TLSv1.2").apply {
        val trustAllCerts = arrayOf<TrustManager>(naiveTrustManager)
        init(null, trustAllCerts, SecureRandom())
    }.socketFactory

    sslSocketFactory(insecureSocketFactory, naiveTrustManager)
    hostnameVerifier(HostnameVerifier { _, _ -> true })
    return this
}

@arulwastaken
Copy link

fun WebView.evol(script: String?, resultCallback: ValueCallback? = null) {
evaluateJavascript(script, resultCallback)
}

fun wrapQuote(value : String): String = "'$value'"

@mmlovesyy
Copy link

var View.isVisible: Boolean
    get() = visibility == View.VISIBLE
    set(value) {
        val v = if (value) View.VISIBLE else View.GONE
        if (visibility != v) {
            visibility = v
        }
    }

// dp -> px
val Number.toPx
    get() = TypedValue.applyDimension(
        TypedValue.COMPLEX_UNIT_DIP,
        this.toFloat(),
        Resources.getSystem().displayMetrics
    )

fun Any?.isNull() = this == null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment