-
Notifications
You must be signed in to change notification settings - Fork 0
Extensions
designsystem-utilities provides various extensions and utilities functions as helpers. Usually the utilities functions are attached to the Companion object of a certain type.
ℹ️ This an utility method in Color.Companion
Convert a hex value string to a Color
- If the conversion fails,
fallbackColorwill be returned - If
hexValueis null,fallbackColorwill be returned - If
fallbackColoris not provided,Color.Whitewill be returned
// valid values
val white = Color.fromHex("#ffffff")
val anotherWhite = Color.fromHex("#FFFFFFFF")
// exception
val exception = Color.fromHex("ffffff")Chain colors values until a color != Color.Unspecified is found.
val color = someColor.ifUnspecified(anotherColor).ifUnspecified(someOthercolor)Creates a RoundedCornerShape from a Dp value.
val shape = 8.dp.toRoundedShape()These are a series of extensions used to avoid using magic strings.
Extensions for String? to return String.empty if the source is null.
val someString: String? = null
val empty = someString.orEmpty()Used to covert a regular String to a AnnotedString.
val annotedString = "some string".toAnnotedString()Covert a String? to Color using Color.fromHex()
The library provides a series of extensions to TypedArray to:
- More easily extract attributes in custom views
- Bridge XML theme/attributes to compose Theme
The provided extensions are: getStringOrEmpty, getBooleanOrTrue, getBooleanOrFalse, getResourceIdOrNull, getComposeColor, getDp.
// example of usage inside a custom view `init` block
// the extensions provide a nice way to have fallback/default values
init {
context.theme.obtainStyledAttributes(
attrs,
R.styleable.EverliButtonView,
0, 0
).apply {
try {
text = getStringOrEmpty(R.styleable.EverliButtonView_text)
variant = enumValueOfOrFallback(getInt(R.styleable.EverliButtonView_btnVariant, variant.ordinal), ButtonVariant.PRIMARY)
isButtonEnabled = getBooleanOrTrue(R.styleable.EverliButtonView_enabled)
useContextTheme = getBooleanOrFalse(R.styleable.EverliButtonView_useContextTheme)
icon = getDrawable(R.styleable.EverliButtonView_btnIcon)
} finally {
recycle()
}
}
}Using the extensions to extract `xml` theme attributes and convert them to `Compose`
context.obtainStyledAttributes(R.styleable.EverliTheme).use { ta ->
val small = ta.getDp(R.styleable.EverliTheme_radiusSmall, density, DefaultRadiusTheme.small)
val primary = ta.getComposeColor(R.styleable.EverliTheme_textColorPrimary, DefaultTextTheme.color.primary)
}