Skip to content

Instantly share code, notes, and snippets.

@adavis
Last active April 2, 2024 20:51
Show Gist options
  • Star 62 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • 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)
@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