Last active
November 18, 2021 10:04
-
-
Save mmlovesyy/75540376ee279d1fbc1796db33c504d1 to your computer and use it in GitHub Desktop.
Frequently used Kotlin extensions for Android
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
```kotlin | |
/** | |
* property extension | |
*/ | |
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 | |
) | |
/** | |
* method extension | |
*/ | |
fun Any?.isNull() = this == null | |
inline fun View.showIf(condition: () -> Boolean): View { | |
if (condition.invoke()) { | |
isVisible = true | |
} | |
return this | |
} | |
fun View.hide(): View { | |
visibility = View.GONE | |
return this | |
} | |
inline fun View.hideIf(condition: () -> Boolean): View { | |
if (condition.invoke()) { | |
visibility = View.GONE | |
} | |
return this | |
} | |
fun View.setPaddingLeft(value: Int) = setPadding(value, paddingTop, paddingRight, paddingBottom) | |
fun View.setPaddingRight(value: Int) = setPadding(paddingLeft, paddingTop, value, paddingBottom) | |
fun View.setPaddingTop(value: Int) = setPadding(paddingLeft, value, paddingRight, paddingBottom) | |
fun View.setPaddingBottom(value: Int) = setPadding(paddingLeft, paddingTop, paddingRight, value) | |
fun TextView.setDrawableLeft(value: Drawable?) = setCompoundDrawables(value, null, null, null) | |
``` |
Author
mmlovesyy
commented
Nov 18, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment