Created
December 19, 2019 14:12
-
-
Save rasheedsulayman/d505487672c616c2f73f09c6daa1e820 to your computer and use it in GitHub Desktop.
A set of common extensions methods. Expecially for getting resources and setting the resource values to various View widgets
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
@SuppressLint("InlinedApi") | |
internal fun Context.getThemeBackgroundColor(): Int { | |
val attributes = theme.obtainStyledAttributes(intArrayOf(android.R.attr.colorBackgroundFloating)) | |
try { | |
return attributes.getColor(0, Color.WHITE) | |
} finally { | |
attributes.recycle() | |
} | |
} | |
internal fun Context.getFont( | |
@FontRes fontRes: Int? = null, | |
font: Typeface? = null | |
): Typeface? = font ?: if (fontRes != null) ResourcesCompat.getFont(this, fontRes) else null | |
internal fun Context.getColor( | |
@ColorRes colorRes: Int? = null, | |
@ColorInt color: Int? = null | |
): Int? = color ?: if (colorRes != null) ContextCompat.getColor(this, colorRes) else null | |
internal fun Context.getDrawableAsset( | |
@DrawableRes iconDrawableRes: Int? = null, | |
iconDrawable: Drawable? = null | |
): Drawable? { | |
return iconDrawable ?: if (iconDrawableRes != null) ContextCompat.getDrawable( | |
this, | |
iconDrawableRes | |
) else null | |
} | |
internal fun Context.getDimension( | |
@DimenRes dimenRes: Int? = null, | |
@Px dimensionInPx: Int? = null | |
): Float? = dimensionInPx?.toFloat() ?: if (dimenRes != null) resources.getDimension(dimenRes) else null | |
internal fun Context.getTextString( | |
@StringRes titleRes: Int? = null, | |
text: String? = null | |
): String? { | |
return text ?: if (titleRes != null) getString(titleRes) else null | |
} | |
internal fun TextView.saveSetText( | |
@StringRes textRes: Int? = null, | |
text: String? = null | |
) { | |
context.getTextString(textRes, text)?.let { | |
setText(it) | |
} | |
} | |
internal fun TextView.saveSetTextColor( | |
@ColorRes colorRes: Int? = null, | |
@ColorInt color: Int? = null | |
) { | |
context.getColor(colorRes, color)?.let { | |
setTextColor(it) | |
} | |
} | |
internal fun ImageView.saveSetIconDrawable( | |
@DrawableRes iconDrawableRes: Int? = null, | |
iconDrawable: Drawable? = null | |
) { | |
context.getDrawableAsset(iconDrawableRes, iconDrawable)?.let { | |
setImageDrawable(it) | |
show() | |
} | |
} | |
internal fun TextView.saveSetTypeFace(@FontRes fontRes: Int? = null, font: Typeface? = null) { | |
context.getFont(fontRes, font)?.let { | |
typeface = it | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment