Context

Compat Color

This function retrieves a color from resources in a backward-compatible way.

fun Context.getCompatColor(@ColorRes resId: Int): Int =
    ContextCompat.getColor(this, resId)
  • Parameters: resId (the resource ID of the color).

  • Process: Uses ContextCompat.getColor to get the color, ensuring compatibility with older versions of Android.

  • Return: The color as an Int.

Example:

val color = context.getCompatColor(R.color.myColor)
view.setBackgroundColor(color)

Compat Drawable

This function retrieves a drawable from resources in a backward-compatible way.

fun Context.getCompatDrawable(@DrawableRes resId: Int): Drawable? =
    ContextCompat.getDrawable(this, resId)
  • Parameters: resId (the resource ID of the drawable).

  • Process: Uses ContextCompat.getDrawable to get the drawable, ensuring compatibility with older versions of Android.

  • Return: The drawable as a Drawable?.

Example:

val drawable = context.getCompatDrawable(R.drawable.myDrawable)
imageView.setImageDrawable(drawable)

Dimen Size

This function retrieves a dimension from resources and converts it to pixels.

fun Context.getDimenSize(@DimenRes resId: Int): Int =
    this.resources.getDimensionPixelSize(resId)
  • Parameters: resId (the resource ID of the dimension).

  • Process: Uses resources.getDimensionPixelSize to get the dimension in pixels.

  • Return: The dimension size in pixels as an Int.

Example:

val padding = context.getDimenSize(R.dimen.myPadding)
view.setPadding(padding, padding, padding, padding)

Get Integer

This function retrieves an integer value from resources.

fun Context.getInteger(@IntegerRes resId: Int): Int =
    this.resources.getInteger(resId)
  • Parameters: resId (the resource ID of the integer).

  • Process: Uses resources.getInteger to get the integer value.

  • Return: The integer value as an Int.

Example:

val maxItems = context.getInteger(R.integer.maxItems)
recyclerView.setMaxItems(maxItems)

Last updated