List of KTX extensions

androidx.activity

Dependency

Groovy

dependencies {
    implementation "androidx.activity:activity-ktx:1.8.2"
}

Kotlin

dependencies {
    implementation("androidx.activity:activity-ktx:1.8.2")
}

Extension functions

For OnBackPressedDispatcher
OnBackPressedCallback OnBackPressedDispatcher.addCallback(owner: LifecycleOwner? = null, enabled: Boolean = true, onBackPressed: OnBackPressedCallback.() -> Unit)

Create and add a new OnBackPressedCallback that calls onBackPressed in OnBackPressedCallback.handleOnBackPressed.

For ComponentActivity
Lazy<VM> ComponentActivity.viewModels(noinline factoryProducer: () -> ViewModelProvider.Factory = null)

Returns a Lazy delegate to access the ComponentActivity's ViewModel, if factoryProducer is specified then ViewModelProvider.Factory returned by it will be used to create ViewModel first time.

androidx.benchmark

Dependency

Groovy

dependencies {
    implementation "androidx.benchmark:benchmark-junit4:1.2.3"
}

Kotlin

dependencies {
    implementation("androidx.benchmark:benchmark-junit4:1.2.3")
}

Top-level functions

Unit beginTraceSection(sectionName: String)

Unit endTraceSection()

androidx.benchmark.junit4

Dependency

Groovy

dependencies {
    implementation "androidx.benchmark:benchmark-junit4:1.2.3"
}

Kotlin

dependencies {
    implementation("androidx.benchmark:benchmark-junit4:1.2.3")
}

Extension functions

For BenchmarkRule
Unit BenchmarkRule.measureRepeated(crossinline block: BenchmarkRule.Scope.() -> Unit)

Benchmark a block of code.

androidx.collection

Dependency

Groovy

dependencies {
    implementation "androidx.collection:collection-ktx:1.4.0"
}

Kotlin

dependencies {
    implementation("androidx.collection:collection-ktx:1.4.0")
}

Extension functions

For LongSparseArray
operator Boolean LongSparseArray<T>.contains(key: Long)

Returns true if the collection contains key.

Unit LongSparseArray<T>.forEach(action: (key: Long, value: T) -> Unit)

Performs the given action for each key/value entry.

T LongSparseArray<T>.getOrDefault(key: Long, defaultValue: T)

Return the value corresponding to key, or defaultValue when not present.

T LongSparseArray<T>.getOrElse(key: Long, defaultValue: () -> T)

Return the value corresponding to key, or from defaultValue when not present.

Boolean LongSparseArray<T>.isNotEmpty()

Return true when the collection contains elements.

LongIterator LongSparseArray<T>.keyIterator()

Return an iterator over the collection's keys.

operator LongSparseArray<T> LongSparseArray<T>.plus(other: LongSparseArray<T>)

Creates a new collection by adding or replacing entries from other.

Boolean LongSparseArray<T>.remove(key: Long, value: T)

Removes the entry for key only if it is mapped to value.

operator Unit LongSparseArray<T>.set(key: Long, value: T)

Allows the use of the index operator for storing values in the collection.

Iterator<T> LongSparseArray<T>.valueIterator()

Return an iterator over the collection's values.

For SparseArrayCompat
operator Boolean SparseArrayCompat<T>.contains(key: Int)

Returns true if the collection contains key.

Unit SparseArrayCompat<T>.forEach(action: (key: Int, value: T) -> Unit)

Performs the given action for each key/value entry.

T SparseArrayCompat<T>.getOrDefault(key: Int, defaultValue: T)

Return the value corresponding to key, or defaultValue when not present.

T SparseArrayCompat<T>.getOrElse(key: Int, defaultValue: () -> T)

Return the value corresponding to key, or from defaultValue when not present.

Boolean SparseArrayCompat<T>.isNotEmpty()

Return true when the collection contains elements.

IntIterator SparseArrayCompat<T>.keyIterator()

Return an iterator over the collection's keys.

operator SparseArrayCompat<T> SparseArrayCompat<T>.plus(other: SparseArrayCompat<T>)

Creates a new collection by adding or replacing entries from other.

Boolean SparseArrayCompat<T>.remove(key: Int, value: T)

Removes the entry for key only if it is mapped to value.

operator Unit SparseArrayCompat<T>.set(key: Int, value: T)

Allows the use of the index operator for storing values in the collection.

Iterator<T> SparseArrayCompat<T>.valueIterator()

Return an iterator over the collection's values.

Extension properties

For LongSparseArray
Int LongSparseArray<T>.size()

Returns the number of key/value pairs in the collection.

For SparseArrayCompat
Int SparseArrayCompat<T>.size()

Returns the number of key/value pairs in the collection.

Top-level functions

ArrayMap<K, V> arrayMapOf()

Returns an empty new ArrayMap.

ArrayMap<K, V> arrayMapOf(vararg pairs: Pair<K, V>)

Returns a new ArrayMap with the specified contents, given as a list of pairs where the first component is the key and the second component is the value.

ArraySet<T> arraySetOf()

Returns an empty new ArraySet.

ArraySet<T> arraySetOf(vararg values: T)

Returns a new ArraySet with the specified contents.

LruCache<K, V> lruCache(maxSize: Int, crossinline sizeOf: (key: K, value: V) -> Int = { _, _ -> 1 }, crossinline create: (key: K) -> V? = { null as V? }, crossinline onEntryRemoved: (evicted: Boolean, key: K, oldValue: V, newValue: V?) -> Unit = { _, _, _, _ -> })

Creates an LruCache with the given parameters.

androidx.core.animation

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.animation.Animator
AnimatorListener Animator.addListener(crossinline onEnd: (animator: Animator) -> Unit = {}, crossinline onStart: (animator: Animator) -> Unit = {}, crossinline onCancel: (animator: Animator) -> Unit = {}, crossinline onRepeat: (animator: Animator) -> Unit = {})

Add a listener to this Animator using the provided actions.

AnimatorPauseListener Animator.addPauseListener(crossinline onResume: (animator: Animator) -> Unit = {}, crossinline onPause: (animator: Animator) -> Unit = {})

Add a pause and resume listener to this Animator using the provided actions.

AnimatorListener Animator.doOnCancel(crossinline action: (animator: Animator) -> Unit)

Add an action which will be invoked when the animation has been cancelled.

AnimatorListener Animator.doOnEnd(crossinline action: (animator: Animator) -> Unit)

Add an action which will be invoked when the animation has ended.

AnimatorPauseListener Animator.doOnPause(crossinline action: (animator: Animator) -> Unit)

Add an action which will be invoked when the animation has been paused.

AnimatorListener Animator.doOnRepeat(crossinline action: (animator: Animator) -> Unit)

Add an action which will be invoked when the animation has repeated.

AnimatorPauseListener Animator.doOnResume(crossinline action: (animator: Animator) -> Unit)

Add an action which will be invoked when the animation has resumed after a pause.

AnimatorListener Animator.doOnStart(crossinline action: (animator: Animator) -> Unit)

Add an action which will be invoked when the animation has started.

androidx.core.content

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.content.Context
T? Context.getSystemService()

Return the handle to a system-level service by class.

Unit Context.withStyledAttributes(set: AttributeSet? = null, attrs: IntArray, @AttrRes defStyleAttr: Int = 0, @StyleRes defStyleRes: Int = 0, block: TypedArray.() -> Unit)

Executes block on a TypedArray receiver.

Unit Context.withStyledAttributes(@StyleRes resourceId: Int, attrs: IntArray, block: TypedArray.() -> Unit)

Executes block on a TypedArray receiver.

For android.content.SharedPreferences
Unit SharedPreferences.edit(commit: Boolean = false, action: Editor.() -> Unit)

Allows editing of this preference instance with a call to apply or commit to persist the changes.

Top-level functions

ContentValues contentValuesOf(vararg pairs: Pair<String, Any?>)

Returns a new ContentValues with the given key/value pairs as elements.

androidx.core.content.res

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.content.res.TypedArray
Boolean TypedArray.getBooleanOrThrow(@StyleableRes index: Int)

Retrieve the boolean value for the attribute at index or throws IllegalArgumentException if not defined.

Int TypedArray.getColorOrThrow(@StyleableRes index: Int)

Retrieve the color value for the attribute at index or throws IllegalArgumentException if not defined.

ColorStateList TypedArray.getColorStateListOrThrow(@StyleableRes index: Int)

Retrieve the color state list value for the attribute at index or throws IllegalArgumentException if not defined.

Float TypedArray.getDimensionOrThrow(@StyleableRes index: Int)

Retrieve the dimension value for the attribute at index or throws IllegalArgumentException if not defined.

Int TypedArray.getDimensionPixelOffsetOrThrow(@StyleableRes index: Int)

Retrieve the dimension pixel offset value for the attribute at index or throws IllegalArgumentException if not defined.

Int TypedArray.getDimensionPixelSizeOrThrow(@StyleableRes index: Int)

Retrieve the dimension pixel size value for the attribute at index or throws IllegalArgumentException if not defined.

Drawable TypedArray.getDrawableOrThrow(@StyleableRes index: Int)

Retrieve the drawable value for the attribute at index or throws IllegalArgumentException if not defined.

Float TypedArray.getFloatOrThrow(@StyleableRes index: Int)

Retrieve the float value for the attribute at index or throws IllegalArgumentException if not defined.

Typeface TypedArray.getFontOrThrow(@StyleableRes index: Int)

Retrieve the font value for the attribute at index or throws IllegalArgumentException if not defined.

Int TypedArray.getIntOrThrow(@StyleableRes index: Int)

Retrieve the integer value for the attribute at index or throws IllegalArgumentException if not defined.

Int TypedArray.getIntegerOrThrow(@StyleableRes index: Int)

Retrieve the integer value for the attribute at index or throws IllegalArgumentException if not defined.

Int TypedArray.getResourceIdOrThrow(@StyleableRes index: Int)

Retrieves the resource identifier for the attribute at index or throws IllegalArgumentException if not defined.

String TypedArray.getStringOrThrow(@StyleableRes index: Int)

Retrieve the string value for the attribute at index or throws IllegalArgumentException if not defined.

Array<CharSequence> TypedArray.getTextArrayOrThrow(@StyleableRes index: Int)

Retrieve the text array value for the attribute at index or throws IllegalArgumentException if not defined.

CharSequence TypedArray.getTextOrThrow(@StyleableRes index: Int)

Retrieve the text value for the attribute at index or throws IllegalArgumentException if not defined.

R TypedArray.use(block: (TypedArray) -> R)

Executes the given block function on this TypedArray and then recycles it.

androidx.core.database

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.database.Cursor
ByteArray? Cursor.getBlobOrNull(index: Int)

Returns the value of the requested column as a nullable byte array.

Double? Cursor.getDoubleOrNull(index: Int)

Returns the value of the requested column as a nullable double.

Float? Cursor.getFloatOrNull(index: Int)

Returns the value of the requested column as a nullable float.

Int? Cursor.getIntOrNull(index: Int)

Returns the value of the requested column as a nullable integer.

Long? Cursor.getLongOrNull(index: Int)

Returns the value of the requested column as a nullable long.

Short? Cursor.getShortOrNull(index: Int)

Returns the value of the requested column as a nullable short.

String? Cursor.getStringOrNull(index: Int)

Returns the value of the requested column as a nullable string.

androidx.core.database.sqlite

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.database.sqlite.SQLiteDatabase
T SQLiteDatabase.transaction(exclusive: Boolean = true, body: SQLiteDatabase.() -> T)

Run body in a transaction marking it as successful if it completes without exception.

androidx.core.graphics

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.graphics.Bitmap
Bitmap Bitmap.applyCanvas(block: Canvas.() -> Unit)

Creates a new Canvas to draw on this bitmap and executes the specified block on the newly created canvas.

operator Boolean Bitmap.contains(p: Point)

Returns true if the specified point is inside the bitmap.

operator Boolean Bitmap.contains(p: PointF)

Returns true if the specified point is inside the bitmap.

operator Int Bitmap.get(x: Int, y: Int)

Returns the value of the pixel at the specified location.

Bitmap Bitmap.scale(width: Int, height: Int, filter: Boolean = true)

Creates a new bitmap, scaled from this bitmap, when possible.

operator Unit Bitmap.set(x: Int, y: Int, color: Int)

Writes the specified color int into the bitmap (assuming it is mutable) at the specified (x, y) coordinate.

For android.graphics.Canvas
Unit Canvas.withClip(clipRect: Rect, block: Canvas.() -> Unit)

Wrap the specified block in calls to Canvas.save/Canvas.clipRect and Canvas.restoreToCount.

Unit Canvas.withClip(clipRect: RectF, block: Canvas.() -> Unit)

Wrap the specified block in calls to Canvas.save/Canvas.clipRect and Canvas.restoreToCount.

Unit Canvas.withClip(left: Int, top: Int, right: Int, bottom: Int, block: Canvas.() -> Unit)

Wrap the specified block in calls to Canvas.save/Canvas.clipRect and Canvas.restoreToCount.

Unit Canvas.withClip(left: Float, top: Float, right: Float, bottom: Float, block: Canvas.() -> Unit)

Wrap the specified block in calls to Canvas.save/Canvas.clipRect and Canvas.restoreToCount.

Unit Canvas.withClip(clipPath: Path, block: Canvas.() -> Unit)

Wrap the specified block in calls to Canvas.save/Canvas.clipPath and Canvas.restoreToCount.

Unit Canvas.withMatrix(matrix: Matrix = Matrix(), block: Canvas.() -> Unit)

Wrap the specified block in calls to Canvas.save/Canvas.concat and Canvas.restoreToCount.

Unit Canvas.withRotation(degrees: Float = 0.0f, pivotX: Float = 0.0f, pivotY: Float = 0.0f, block: Canvas.() -> Unit)

Wrap the specified block in calls to Canvas.save/Canvas.rotate and Canvas.restoreToCount.

Unit Canvas.withSave(block: Canvas.() -> Unit)

Wrap the specified block in calls to Canvas.save and Canvas.restoreToCount.

Unit Canvas.withScale(x: Float = 1.0f, y: Float = 1.0f, pivotX: Float = 0.0f, pivotY: Float = 0.0f, block: Canvas.() -> Unit)

Wrap the specified block in calls to Canvas.save/Canvas.scale and Canvas.restoreToCount.

Unit Canvas.withSkew(x: Float = 0.0f, y: Float = 0.0f, block: Canvas.() -> Unit)

Wrap the specified block in calls to Canvas.save/Canvas.skew and Canvas.restoreToCount.

Unit Canvas.withTranslation(x: Float = 0.0f, y: Float = 0.0f, block: Canvas.() -> Unit)

Wrap the specified block in calls to Canvas.save/Canvas.translate and Canvas.restoreToCount.

For android.graphics.Color
operator Float Color.component1()

Returns the first component of the color.

operator Float Color.component2()

Returns the second component of the color.

operator Float Color.component3()

Returns the third component of the color.

operator Float Color.component4()

Returns the fourth component of the color.

infix Color! Color.convertTo(colorSpace: Named)

Converts the color receiver to a color in the specified color space.

infix Color! Color.convertTo(colorSpace: ColorSpace)

Converts the color receiver to a color in the specified color space.

operator Color Color.plus(c: Color)

Composites two translucent colors together.

For android.graphics.ImageDecoder.Source
Bitmap Source.decodeBitmap(crossinline action: ImageDecoder.(info: ImageInfo, source: Source) -> Unit)

Create a Bitmap from a Source

Drawable Source.decodeDrawable(crossinline action: ImageDecoder.(info: ImageInfo, source: Source) -> Unit)

Create a Drawable from a Source

For android.graphics.Matrix
operator Matrix Matrix.times(m: Matrix)

Multiplies this Matrix by another matrix and returns the result as a new matrix.

FloatArray Matrix.values()

Returns the 9 values of this Matrix as a new array of floats.

For android.graphics.Paint
Boolean Paint.setBlendMode(blendModeCompat: BlendModeCompat?)

Convenience method to configure the BlendMode of a Paint in a backward compatible way.

For android.graphics.Path
infix Path Path.and(p: Path)

Returns the intersection of two paths as a new Path.

Iterable<PathSegment> Path.flatten(error: Float = 0.5f)

Flattens (or approximate) the Path with a series of line segments.

operator Path Path.minus(p: Path)

Returns the difference of two paths as a new Path.

infix Path Path.or(p: Path)

Returns the union of two paths as a new Path.

operator Path Path.plus(p: Path)

Returns the union of two paths as a new Path.

infix Path Path.xor(p: Path)

Returns the union minus the intersection of two paths as a new Path.

For android.graphics.Picture
Picture Picture.record(width: Int, height: Int, block: Canvas.() -> Unit)

Creates a new Canvas to record commands in this Picture, executes the specified block on the newly created canvas and returns this Picture.

For android.graphics.Point
operator Int Point.component1()

Returns the x coordinate of this point.

operator Int Point.component2()

Returns the y coordinate of this point.

operator Point Point.minus(p: Point)

Offsets this point by the negation of the specified point and returns the result as a new point.

operator Point Point.minus(xy: Int)

Offsets this point by the negation of the specified amount on both X and Y axis and returns the result as a new point.

operator Point Point.plus(p: Point)

Offsets this point by the specified point and returns the result as a new point.

operator Point Point.plus(xy: Int)

Offsets this point by the specified amount on both X and Y axis and returns the result as a new point.

PointF Point.toPointF()

Returns a PointF representation of this point.

operator Point Point.unaryMinus()

Returns a new point representing the negation of this point.

For android.graphics.PointF
operator Float PointF.component1()

Returns the x coordinate of this point.

operator Float PointF.component2()

Returns the y coordinate of this point.

operator PointF PointF.minus(p: PointF)

Offsets this point by the negation of the specified point and returns the result as a new point.

operator PointF PointF.minus(xy: Float)

Offsets this point by the negation of the specified amount on both X and Y axis and returns the result as a new point.

operator PointF PointF.plus(p: PointF)

Offsets this point by the specified point and returns the result as a new point.

operator PointF PointF.plus(xy: Float)

Offsets this point by the specified amount on both X and Y axis and returns the result as a new point.

Point PointF.toPoint()

Returns a Point representation of this point.

operator PointF PointF.unaryMinus()

Returns a new point representing the negation of this point.

For android.graphics.PorterDuff.Mode
PorterDuffColorFilter Mode.toColorFilter(color: Int)

Creates a new PorterDuffColorFilter that uses this PorterDuff.Mode as the alpha compositing or blending mode, and the specified color.

PorterDuffXfermode Mode.toXfermode()

Creates a new PorterDuffXfermode that uses this PorterDuff.Mode as the alpha compositing or blending mode.

For android.graphics.Rect
infix Rect Rect.and(r: Rect)

Returns the intersection of two rectangles as a new rectangle.

operator Int Rect.component1()

Returns "left", the first component of the rectangle.

operator Int Rect.component2()

Returns "top", the second component of the rectangle.

operator Int Rect.component3()

Returns "right", the third component of the rectangle.

operator Int Rect.component4()

Returns "bottom", the fourth component of the rectangle.

operator Boolean Rect.contains(p: Point)

Returns true if the specified point is inside the rectangle.

operator Region Rect.minus(r: Rect)

Returns the difference of this rectangle and the specified rectangle as a new region.

operator Rect Rect.minus(xy: Int)

Returns a new rectangle representing this rectangle offset by the negation of the specified amount on both X and Y axis.

operator Rect Rect.minus(xy: Point)

Returns a new rectangle representing this rectangle offset by the negation of the specified point.

infix Rect Rect.or(r: Rect)

Returns the union of two rectangles as a new rectangle.

operator Rect Rect.plus(r: Rect)

Performs the union of this rectangle and the specified rectangle and returns the result as a new rectangle.

operator Rect Rect.plus(xy: Int)

Returns a new rectangle representing this rectangle offset by the specified amount on both X and Y axis.

operator Rect Rect.plus(xy: Point)

Returns a new rectangle representing this rectangle offset by the specified point.

operator Rect Rect.times(factor: Int)

Returns a new rectangle representing this rectangle's components each scaled by factor.

RectF Rect.toRectF()

Returns a RectF representation of this rectangle.

Region Rect.toRegion()

Returns a Region representation of this rectangle.

infix Region Rect.xor(r: Rect)

Returns the union minus the intersection of two rectangles as a new region.

For android.graphics.RectF
infix RectF RectF.and(r: RectF)

Returns the intersection of two rectangles as a new rectangle.

operator Float RectF.component1()

Returns "left", the first component of the rectangle.

operator Float RectF.component2()

Returns "top", the second component of the rectangle.

operator Float RectF.component3()

Returns "right", the third component of the rectangle.

operator Float RectF.component4()

Returns "bottom", the fourth component of the rectangle.

operator Boolean RectF.contains(p: PointF)

Returns true if the specified point is inside the rectangle.

operator Region RectF.minus(r: RectF)

Returns the difference of this rectangle and the specified rectangle as a new region.

operator RectF RectF.minus(xy: Float)

Returns a new rectangle representing this rectangle offset by the negation of the specified amount on both X and Y axis.

operator RectF RectF.minus(xy: PointF)

Returns a new rectangle representing this rectangle offset by the negation of the specified point.

infix RectF RectF.or(r: RectF)

Returns the union of two rectangles as a new rectangle.

operator RectF RectF.plus(r: RectF)

Performs the union of this rectangle and the specified rectangle and returns the result as a new rectangle.

operator RectF RectF.plus(xy: Float)

Returns a new rectangle representing this rectangle offset by the specified amount on both X and Y axis.

operator RectF RectF.plus(xy: PointF)

Returns a new rectangle representing this rectangle offset by the specified point.

operator RectF RectF.times(factor: Int)

Returns a new rectangle representing this rectangle's components each scaled by factor.

operator RectF RectF.times(factor: Float)

Returns a new rectangle representing this rectangle's components each scaled by factor.

Rect RectF.toRect()

Returns a Rect representation of this rectangle.

Region RectF.toRegion()

Returns a Region representation of this rectangle.

RectF RectF.transform(m: Matrix)

Transform this rectangle in place using the supplied Matrix and returns this rectangle.

infix Region RectF.xor(r: RectF)

Returns the union minus the intersection of two rectangles as a new region.

For android.graphics.Region
infix Region Region.and(r: Rect)

Return the intersection of this region and the specified Rect as a new region.

infix Region Region.and(r: Region)

Return the intersection of this region and the specified region as a new region.

operator Boolean Region.contains(p: Point)

Return true if the region contains the specified Point.

Unit Region.forEach(action: (rect: Rect) -> Unit)

Performs the given action on each rect in this region.

operator Iterator<Rect> Region.iterator()

Returns an Iterator over the rects in this region.

operator Region Region.minus(r: Rect)

Return the difference of this region and the specified Rect as a new region.

operator Region Region.minus(r: Region)

Return the difference of this region and the specified region as a new region.

operator Region Region.not()

Returns the negation of this region as a new region.

infix Region Region.or(r: Rect)

Return the union of this region and the specified Rect as a new region.

infix Region Region.or(r: Region)

Return the union of this region and the specified region as a new region.

operator Region Region.plus(r: Rect)

Return the union of this region and the specified Rect as a new region.

operator Region Region.plus(r: Region)

Return the union of this region and the specified region as a new region.

operator Region Region.unaryMinus()

Returns the negation of this region as a new region.

infix Region Region.xor(r: Rect)

Return the union minus the intersection of this region and the specified Rect as a new region.

infix Region Region.xor(r: Region)

Return the union minus the intersection of this region and the specified region as a new region.

For android.graphics.Shader
Unit Shader.transform(block: Matrix.() -> Unit)

Wrap the specified block in calls to Shader.getLocalMatrix and Shader.setLocalMatrix.

For kotlin.Int
operator Int Int.component1()

Return the alpha component of a color int.

operator Int Int.component2()

Return the red component of a color int.

operator Int Int.component3()

Return the green component of a color int.

operator Int Int.component4()

Return the blue component of a color int.

infix Long Int.convertTo(colorSpace: Named)

Converts the color int receiver to a color long in the specified color space.

infix Long Int.convertTo(colorSpace: ColorSpace)

Converts the color int receiver to a color long in the specified color space.

Color Int.toColor()

Creates a new Color instance from a color int.

Long Int.toColorLong()

Converts the specified ARGB color int to an RGBA color long in the sRGB color space.

For kotlin.Long
operator Float Long.component1()

Returns the first component of the color.

operator Float Long.component2()

Returns the second component of the color.

operator Float Long.component3()

Returns the third component of the color.

operator Float Long.component4()

Returns the fourth component of the color.

infix Long Long.convertTo(colorSpace: Named)

Converts the color long receiver to a color long in the specified color space.

infix Long Long.convertTo(colorSpace: ColorSpace)

Converts the color long receiver to a color long in the specified color space.

Color Long.toColor()

Creates a new Color instance from a color long.

Int Long.toColorInt()

Converts the specified color long to an ARGB color int.

For kotlin.String
Int String.toColorInt()

Return a corresponding Int color of this String.

Extension properties

For kotlin.Int
Int Int.alpha()

Return the alpha component of a color int.

Int Int.blue()

Return the blue component of a color int.

Int Int.green()

Return the green component of a color int.

Float Int.luminance()

Returns the relative luminance of a color int, assuming sRGB encoding.

Int Int.red()

Return the red component of a color int.

For kotlin.Long
Float Long.alpha()

Return the alpha component of a color long.

Float Long.blue()

Return the blue component of a color long.

ColorSpace Long.colorSpace()

Returns the color space encoded in the specified color long.

Float Long.green()

Return the green component of a color long.

Boolean Long.isSrgb()

Indicates whether the color is in the sRGB color space.

Boolean Long.isWideGamut()

Indicates whether the color is in a wide-gamut color space.

Float Long.luminance()

Returns the relative luminance of a color.

Float Long.red()

Return the red component of a color long.

Top-level functions

Bitmap createBitmap(width: Int, height: Int, config: Config = Bitmap.Config.ARGB_8888)

Returns a mutable bitmap with the specified width and height.

Bitmap createBitmap(width: Int, height: Int, config: Config = Bitmap.Config.ARGB_8888, hasAlpha: Boolean = true, colorSpace: ColorSpace = ColorSpace.get(ColorSpace.Named.SRGB))

Returns a mutable bitmap with the specified width and height.

Matrix rotationMatrix(degrees: Float, px: Float = 0.0f, py: Float = 0.0f)

Creates a rotation matrix, defined by a rotation angle in degrees around the pivot point located at the coordinates (px, py).

Matrix scaleMatrix(sx: Float = 1.0f, sy: Float = 1.0f)

Creates a scale matrix with the scale factor sx and sy respectively on the x and y axis.

Matrix translationMatrix(tx: Float = 0.0f, ty: Float = 0.0f)

Creates a translation matrix with the translation amounts tx and ty respectively on the x and y axis.

androidx.core.graphics.drawable

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.graphics.Bitmap
Icon Bitmap.toAdaptiveIcon()

Create an Icon from this adaptive Bitmap.

BitmapDrawable Bitmap.toDrawable(resources: Resources)

Create a BitmapDrawable from this Bitmap.

Icon Bitmap.toIcon()

Create an Icon from this Bitmap.

For android.graphics.Color
ColorDrawable Color.toDrawable()

Create a ColorDrawable from this Color (via Color.toArgb).

For android.graphics.drawable.Drawable
Bitmap Drawable.toBitmap(@Px width: Int = intrinsicWidth, @Px height: Int = intrinsicHeight, config: Config? = null)

Return a Bitmap representation of this Drawable.

Unit Drawable.updateBounds(@Px left: Int = bounds.left, @Px top: Int = bounds.top, @Px right: Int = bounds.right, @Px bottom: Int = bounds.bottom)

Updates this drawable's bounds.

For android.net.Uri
Icon Uri.toIcon()

Create an Icon from this Uri.

For kotlin.ByteArray
Icon ByteArray.toIcon()

Create an Icon from this ByteArray.

For kotlin.Int
ColorDrawable Int.toDrawable()

Create a ColorDrawable from this color value.

androidx.core.location

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.location.Location
operator Double Location.component1()

Returns the latitude of this Location.

operator Double Location.component2()

Returns the longitude of this Location.

androidx.core.net

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.net.Uri
File Uri.toFile()

Creates a File from the given Uri.

For java.io.File
Uri File.toUri()

Creates a Uri from the given file.

For kotlin.String
Uri String.toUri()

Creates a Uri from the given encoded URI string.

androidx.core.os

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.os.Handler
Runnable Handler.postAtTime(uptimeMillis: Long, token: Any? = null, crossinline action: () -> Unit)

Version of Handler.postAtTime which re-orders the parameters, allowing the action to be placed outside of parentheses.

Runnable Handler.postDelayed(delayInMillis: Long, token: Any? = null, crossinline action: () -> Unit)

Version of Handler.postDelayed which re-orders the parameters, allowing the action to be placed outside of parentheses.

Top-level functions

Bundle bundleOf(vararg pairs: Pair<String, Any?>)

Returns a new Bundle with the given key/value pairs as elements.

PersistableBundle persistableBundleOf(vararg pairs: Pair<String, Any?>)

Returns a new PersistableBundle with the given key/value pairs as elements.

T trace(sectionName: String, block: () -> T)

Wrap the specified block in calls to Trace.beginSection (with the supplied sectionName) and Trace.endSection.

androidx.core.text

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.text.Spannable
Unit Spannable.clearSpans()

Clear all spans from this text.

operator Unit Spannable.set(start: Int, end: Int, span: Any)

Add span to the range start&hellip;end of the text.

operator Unit Spannable.set(range: IntRange, span: Any)

Add span to the range of the text.

For android.text.SpannableStringBuilder
SpannableStringBuilder SpannableStringBuilder.backgroundColor(color: Int, builderAction: SpannableStringBuilder.() -> Unit)

Wrap appended text in builderAction in a BackgroundColorSpan.

SpannableStringBuilder SpannableStringBuilder.bold(builderAction: SpannableStringBuilder.() -> Unit)

Wrap appended text in builderAction in a bold StyleSpan.

SpannableStringBuilder SpannableStringBuilder.color(color: Int, builderAction: SpannableStringBuilder.() -> Unit)

Wrap appended text in builderAction in a ForegroundColorSpan.

SpannableStringBuilder SpannableStringBuilder.inSpans(vararg spans: Any, builderAction: SpannableStringBuilder.() -> Unit)

Wrap appended text in builderAction in spans.

SpannableStringBuilder SpannableStringBuilder.inSpans(span: Any, builderAction: SpannableStringBuilder.() -> Unit)

Wrap appended text in builderAction in span.

SpannableStringBuilder SpannableStringBuilder.italic(builderAction: SpannableStringBuilder.() -> Unit)

Wrap appended text in builderAction in an italic StyleSpan.

SpannableStringBuilder SpannableStringBuilder.scale(proportion: Float, builderAction: SpannableStringBuilder.() -> Unit)

Wrap appended text in builderAction in a RelativeSizeSpan.

SpannableStringBuilder SpannableStringBuilder.strikeThrough(builderAction: SpannableStringBuilder.() -> Unit)

Wrap appended text in builderAction in a StrikethroughSpan.

SpannableStringBuilder SpannableStringBuilder.subscript(builderAction: SpannableStringBuilder.() -> Unit)

Wrap appended text in builderAction in a SubscriptSpan.

SpannableStringBuilder SpannableStringBuilder.superscript(builderAction: SpannableStringBuilder.() -> Unit)

Wrap appended text in builderAction in a SuperscriptSpan.

SpannableStringBuilder SpannableStringBuilder.underline(builderAction: SpannableStringBuilder.() -> Unit)

Wrap appended text in builderAction in an UnderlineSpan.

For android.text.Spanned
Array<out T> Spanned.getSpans(start: Int = 0, end: Int = length)

Get all spans that are instance of T.

String Spanned.toHtml(option: Int = TO_HTML_PARAGRAPH_LINES_CONSECUTIVE)

Returns a string of HTML from the spans in this Spanned.

For kotlin.CharSequence
Boolean CharSequence.isDigitsOnly()

Returns whether the given CharSequence contains only digits.

Spannable CharSequence.toSpannable()

Returns a new Spannable from CharSequence, or the source itself if it is already an instance of SpannableString.

Spanned CharSequence.toSpanned()

Returns a new Spanned from CharSequence, or the source itself if it is already an instance of SpannedString.

Int CharSequence.trimmedLength()

Returns the length that the specified CharSequence would have if spaces and ASCII control characters were trimmed from the start and end, as by String.trim.

For kotlin.String
String String.htmlEncode()

Html-encode the string.

Spanned String.parseAsHtml(flags: Int = FROM_HTML_MODE_LEGACY, imageGetter: ImageGetter? = null, tagHandler: TagHandler? = null)

Returns a Spanned from parsing this string as HTML.

Extension properties

For java.util.Locale
Int Locale.layoutDirection()

Returns layout direction for a given locale.

Top-level functions

SpannedString buildSpannedString(builderAction: SpannableStringBuilder.() -> Unit)

Builds new string by populating a newly created SpannableStringBuilder using the provided builderAction and then converting it to SpannedString.

androidx.core.transition

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.transition.Transition
TransitionListener Transition.addListener(crossinline onEnd: (transition: Transition) -> Unit = {}, crossinline onStart: (transition: Transition) -> Unit = {}, crossinline onCancel: (transition: Transition) -> Unit = {}, crossinline onResume: (transition: Transition) -> Unit = {}, crossinline onPause: (transition: Transition) -> Unit = {})

Add a listener to this Transition using the provided actions.

TransitionListener Transition.doOnCancel(crossinline action: (transition: Transition) -> Unit)

Add an action which will be invoked when this transition has been cancelled.

TransitionListener Transition.doOnEnd(crossinline action: (transition: Transition) -> Unit)

Add an action which will be invoked when this transition has ended.

TransitionListener Transition.doOnPause(crossinline action: (transition: Transition) -> Unit)

Add an action which will be invoked when this transition has been paused.

TransitionListener Transition.doOnResume(crossinline action: (transition: Transition) -> Unit)

Add an action which will be invoked when this transition has resumed after a pause.

TransitionListener Transition.doOnStart(crossinline action: (transition: Transition) -> Unit)

Add an action which will be invoked when this transition has started.

androidx.core.util

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.util.AtomicFile
ByteArray AtomicFile.readBytes()

Gets the entire content of this file as a byte array.

String AtomicFile.readText(charset: Charset = Charsets.UTF_8)

Gets the entire content of this file as a String using UTF-8 or specified charset.

Unit AtomicFile.tryWrite(block: (out: FileOutputStream) -> Unit)

Perform the write operations inside block on this file.

Unit AtomicFile.writeBytes(array: ByteArray)

Sets the content of this file as an array of bytes.

Unit AtomicFile.writeText(text: String, charset: Charset = Charsets.UTF_8)

Sets the content of this file as text encoded using UTF-8 or specified charset.

For android.util.LongSparseArray
operator Boolean LongSparseArray<T>.contains(key: Long)

Returns true if the collection contains key.

Boolean LongSparseArray<T>.containsKey(key: Long)

Returns true if the collection contains key.

Boolean LongSparseArray<T>.containsValue(value: T)

Returns true if the collection contains value.

Unit LongSparseArray<T>.forEach(action: (key: Long, value: T) -> Unit)

Performs the given action for each key/value entry.

T LongSparseArray<T>.getOrDefault(key: Long, defaultValue: T)

Return the value corresponding to key, or defaultValue when not present.

T LongSparseArray<T>.getOrElse(key: Long, defaultValue: () -> T)

Return the value corresponding to key, or from defaultValue when not present.

Boolean LongSparseArray<T>.isEmpty()

Return true when the collection contains no elements.

Boolean LongSparseArray<T>.isNotEmpty()

Return true when the collection contains elements.

LongIterator LongSparseArray<T>.keyIterator()

Return an iterator over the collection's keys.

operator LongSparseArray<T> LongSparseArray<T>.plus(other: LongSparseArray<T>)

Creates a new collection by adding or replacing entries from other.

Unit LongSparseArray<T>.putAll(other: LongSparseArray<T>)

Update this collection by adding or replacing entries from other.

Boolean LongSparseArray<T>.remove(key: Long, value: T)

Removes the entry for key only if it is mapped to value.

operator Unit LongSparseArray<T>.set(key: Long, value: T)

Allows the use of the index operator for storing values in the collection.

Iterator<T> LongSparseArray<T>.valueIterator()

Return an iterator over the collection's values.

For android.util.Pair
operator F Pair<F, S>.component1()

Returns the first component of the pair.

operator S Pair<F, S>.component2()

Returns the second component of the pair.

Pair<F, S> Pair<F, S>.toKotlinPair()

Returns this Pair as a kotlin.Pair.

For android.util.Range
infix Range<T> Range<T>.and(other: Range<T>)

Return the intersection of this range and other.

operator Range<T> Range<T>.plus(value: T)

Return the smallest range that includes this and value.

operator Range<T> Range<T>.plus(other: Range<T>)

Return the smallest range that includes this and other.

ClosedRange<T> Range<T>.toClosedRange()

Returns this Range as a ClosedRange.

For android.util.Size
operator Int Size.component1()

Returns "width", the first component of this Size.

operator Int Size.component2()

Returns "height", the second component of this Size.

For android.util.SizeF
operator Float SizeF.component1()

Returns "width", the first component of this SizeF.

operator Float SizeF.component2()

Returns "height", the second component of this SizeF.

For android.util.SparseArray
operator Boolean SparseArray<T>.contains(key: Int)

Returns true if the collection contains key.

Boolean SparseArray<T>.containsKey(key: Int)

Returns true if the collection contains key.

Boolean SparseArray<T>.containsValue(value: T)

Returns true if the collection contains value.

Unit SparseArray<T>.forEach(action: (key: Int, value: T) -> Unit)

Performs the given action for each key/value entry.

T SparseArray<T>.getOrDefault(key: Int, defaultValue: T)

Return the value corresponding to key, or defaultValue when not present.

T SparseArray<T>.getOrElse(key: Int, defaultValue: () -> T)

Return the value corresponding to key, or from defaultValue when not present.

Boolean SparseArray<T>.isEmpty()

Return true when the collection contains no elements.

Boolean SparseArray<T>.isNotEmpty()

Return true when the collection contains elements.

IntIterator SparseArray<T>.keyIterator()

Return an iterator over the collection's keys.

operator SparseArray<T> SparseArray<T>.plus(other: SparseArray<T>)

Creates a new collection by adding or replacing entries from other.

Unit SparseArray<T>.putAll(other: SparseArray<T>)

Update this collection by adding or replacing entries from other.

Boolean SparseArray<T>.remove(key: Int, value: T)

Removes the entry for key only if it is mapped to value.

operator Unit SparseArray<T>.set(key: Int, value: T)

Allows the use of the index operator for storing values in the collection.

Iterator<T> SparseArray<T>.valueIterator()

Return an iterator over the collection's values.

For android.util.SparseBooleanArray
operator Boolean SparseBooleanArray.contains(key: Int)

Returns true if the collection contains key.

Boolean SparseBooleanArray.containsKey(key: Int)

Returns true if the collection contains key.

Boolean SparseBooleanArray.containsValue(value: Boolean)

Returns true if the collection contains value.

Unit SparseBooleanArray.forEach(action: (key: Int, value: Boolean) -> Unit)

Performs the given action for each key/value entry.

Boolean SparseBooleanArray.getOrDefault(key: Int, defaultValue: Boolean)

Return the value corresponding to key, or defaultValue when not present.

Boolean SparseBooleanArray.getOrElse(key: Int, defaultValue: () -> Boolean)

Return the value corresponding to key, or from defaultValue when not present.

Boolean SparseBooleanArray.isEmpty()

Return true when the collection contains no elements.

Boolean SparseBooleanArray.isNotEmpty()

Return true when the collection contains elements.

IntIterator SparseBooleanArray.keyIterator()

Return an iterator over the collection's keys.

operator SparseBooleanArray SparseBooleanArray.plus(other: SparseBooleanArray)

Creates a new collection by adding or replacing entries from other.

Unit SparseBooleanArray.putAll(other: SparseBooleanArray)

Update this collection by adding or replacing entries from other.

Boolean SparseBooleanArray.remove(key: Int, value: Boolean)

Removes the entry for key only if it is mapped to value.

operator Unit SparseBooleanArray.set(key: Int, value: Boolean)

Allows the use of the index operator for storing values in the collection.

BooleanIterator SparseBooleanArray.valueIterator()

Return an iterator over the collection's values.

For android.util.SparseIntArray
operator Boolean SparseIntArray.contains(key: Int)

Returns true if the collection contains key.

Boolean SparseIntArray.containsKey(key: Int)

Returns true if the collection contains key.

Boolean SparseIntArray.containsValue(value: Int)

Returns true if the collection contains value.

Unit SparseIntArray.forEach(action: (key: Int, value: Int) -> Unit)

Performs the given action for each key/value entry.

Int SparseIntArray.getOrDefault(key: Int, defaultValue: Int)

Return the value corresponding to key, or defaultValue when not present.

Int SparseIntArray.getOrElse(key: Int, defaultValue: () -> Int)

Return the value corresponding to key, or from defaultValue when not present.

Boolean SparseIntArray.isEmpty()

Return true when the collection contains no elements.

Boolean SparseIntArray.isNotEmpty()

Return true when the collection contains elements.

IntIterator SparseIntArray.keyIterator()

Return an iterator over the collection's keys.

operator SparseIntArray SparseIntArray.plus(other: SparseIntArray)

Creates a new collection by adding or replacing entries from other.

Unit SparseIntArray.putAll(other: SparseIntArray)

Update this collection by adding or replacing entries from other.

Boolean SparseIntArray.remove(key: Int, value: Int)

Removes the entry for key only if it is mapped to value.

operator Unit SparseIntArray.set(key: Int, value: Int)

Allows the use of the index operator for storing values in the collection.

IntIterator SparseIntArray.valueIterator()

Return an iterator over the collection's values.

For android.util.SparseLongArray
operator Boolean SparseLongArray.contains(key: Int)

Returns true if the collection contains key.

Boolean SparseLongArray.containsKey(key: Int)

Returns true if the collection contains key.

Boolean SparseLongArray.containsValue(value: Long)

Returns true if the collection contains value.

Unit SparseLongArray.forEach(action: (key: Int, value: Long) -> Unit)

Performs the given action for each key/value entry.

Long SparseLongArray.getOrDefault(key: Int, defaultValue: Long)

Return the value corresponding to key, or defaultValue when not present.

Long SparseLongArray.getOrElse(key: Int, defaultValue: () -> Long)

Return the value corresponding to key, or from defaultValue when not present.

Boolean SparseLongArray.isEmpty()

Return true when the collection contains no elements.

Boolean SparseLongArray.isNotEmpty()

Return true when the collection contains elements.

IntIterator SparseLongArray.keyIterator()

Return an iterator over the collection's keys.

operator SparseLongArray SparseLongArray.plus(other: SparseLongArray)

Creates a new collection by adding or replacing entries from other.

Unit SparseLongArray.putAll(other: SparseLongArray)

Update this collection by adding or replacing entries from other.

Boolean SparseLongArray.remove(key: Int, value: Long)

Removes the entry for key only if it is set to value.

operator Unit SparseLongArray.set(key: Int, value: Long)

Allows the use of the index operator for storing values in the collection.

LongIterator SparseLongArray.valueIterator()

Return an iterator over the collection's values.

For kotlin.Double
Half Double.toHalf()

Returns a Half instance representing given Double.

For kotlin.Float
Half Float.toHalf()

Returns a Half instance representing given Float.

For kotlin.Pair
Pair<F, S> Pair<F, S>.toAndroidPair()

Returns this kotlin.Pair as an Android Pair.

For kotlin.Short
Half Short.toHalf()

Returns a Half instance representing given Short.

For kotlin.String
Half String.toHalf()

Returns a Half instance representing given String.

For kotlin.ranges.ClosedRange
Range<T> ClosedRange<T>.toRange()

Returns this ClosedRange as a Range.

Extension properties

For android.util.LongSparseArray
Int LongSparseArray<T>.size()

Returns the number of key/value pairs in the collection.

For android.util.SparseArray
Int SparseArray<T>.size()

Returns the number of key/value pairs in the collection.

For android.util.SparseBooleanArray
Int SparseBooleanArray.size()

Returns the number of key/value pairs in the collection.

For android.util.SparseIntArray
Int SparseIntArray.size()

Returns the number of key/value pairs in the collection.

For android.util.SparseLongArray
Int SparseLongArray.size()

Returns the number of key/value entries in the collection.

Top-level functions

LruCache<K, V> lruCache(maxSize: Int, crossinline sizeOf: (key: K, value: V) -> Int = { _, _ -> 1 }, crossinline create: (key: K) -> V? = { null as V? }, crossinline onEntryRemoved: (evicted: Boolean, key: K, oldValue: V, newValue: V?) -> Unit = { _, _, _, _ -> })

Creates an LruCache with the given parameters.

infix Range<T> T.rangeTo(that: T)

Creates a range from this Comparable value to that.

androidx.core.view

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.view.Menu
operator Boolean Menu.contains(item: MenuItem)

Returns true if item is found in this menu.

Unit Menu.forEach(action: (item: MenuItem) -> Unit)

Performs the given action on each item in this menu.

Unit Menu.forEachIndexed(action: (index: Int, item: MenuItem) -> Unit)

Performs the given action on each item in this menu, providing its sequential index.

operator MenuItem Menu.get(index: Int)

Returns the menu at index.

Boolean Menu.isEmpty()

Returns true if this menu contains no items.

Boolean Menu.isNotEmpty()

Returns true if this menu contains one or more items.

operator MutableIterator<MenuItem> Menu.iterator()

Returns a MutableIterator over the items in this menu.

operator Unit Menu.minusAssign(item: MenuItem)

Removes item from this menu.

For android.view.View
Unit View.doOnAttach(crossinline action: (view: View) -> Unit)

Performs the given action when this view is attached to a window.

Unit View.doOnDetach(crossinline action: (view: View) -> Unit)

Performs the given action when this view is detached from a window.

Unit View.doOnLayout(crossinline action: (view: View) -> Unit)

Performs the given action when this view is laid out.

Unit View.doOnNextLayout(crossinline action: (view: View) -> Unit)

Performs the given action when this view is next laid out.

OneShotPreDrawListener View.doOnPreDraw(crossinline action: (view: View) -> Unit)

Performs the given action when the view tree is about to be drawn.

Bitmap View.drawToBitmap(config: Config = Bitmap.Config.ARGB_8888)

Return a Bitmap representation of this View.

Runnable View.postDelayed(delayInMillis: Long, crossinline action: () -> Unit)

Version of View.postDelayed which re-orders the parameters, allowing the action to be placed outside of parentheses.

Runnable View.postOnAnimationDelayed(delayInMillis: Long, crossinline action: () -> Unit)

Version of View.postOnAnimationDelayed which re-orders the parameters, allowing the action to be placed outside of parentheses.

Unit View.setPadding(@Px size: Int)

Sets the view's padding.

Unit View.updateLayoutParams(block: LayoutParams.() -> Unit)

Executes block with the View's layoutParams and reassigns the layoutParams with the updated version.

Unit View.updateLayoutParams(block: T.() -> Unit)

Executes block with a typed version of the View's layoutParams and reassigns the layoutParams with the updated version.

Unit View.updatePadding(@Px left: Int = paddingLeft, @Px top: Int = paddingTop, @Px right: Int = paddingRight, @Px bottom: Int = paddingBottom)

Updates this view's padding.

Unit View.updatePaddingRelative(@Px start: Int = paddingStart, @Px top: Int = paddingTop, @Px end: Int = paddingEnd, @Px bottom: Int = paddingBottom)

Updates this view's relative padding.

For android.view.ViewGroup
operator Boolean ViewGroup.contains(view: View)

Returns true if view is found in this view group.

Unit ViewGroup.forEach(action: (view: View) -> Unit)

Performs the given action on each view in this view group.

Unit ViewGroup.forEachIndexed(action: (index: Int, view: View) -> Unit)

Performs the given action on each view in this view group, providing its sequential index.

operator View ViewGroup.get(index: Int)

Returns the view at index.

Boolean ViewGroup.isEmpty()

Returns true if this view group contains no views.

Boolean ViewGroup.isNotEmpty()

Returns true if this view group contains one or more views.

operator MutableIterator<View> ViewGroup.iterator()

Returns a MutableIterator over the views in this view group.

operator Unit ViewGroup.minusAssign(view: View)

Removes view from this view group.

operator Unit ViewGroup.plusAssign(view: View)

Adds view to this view group.

For android.view.ViewGroup.MarginLayoutParams
Unit MarginLayoutParams.setMargins(@Px size: Int)

Sets the margins in the ViewGroup's MarginLayoutParams.

Unit MarginLayoutParams.updateMargins(@Px left: Int = leftMargin, @Px top: Int = topMargin, @Px right: Int = rightMargin, @Px bottom: Int = bottomMargin)

Updates the margins in the ViewGroup's ViewGroup.MarginLayoutParams.

Unit MarginLayoutParams.updateMarginsRelative(@Px start: Int = marginStart, @Px top: Int = topMargin, @Px end: Int = marginEnd, @Px bottom: Int = bottomMargin)

Updates the relative margins in the ViewGroup's MarginLayoutParams.

Extension properties

For android.view.Menu
Sequence<MenuItem> Menu.children()

Returns a Sequence over the items in this menu.

Int Menu.size()

Returns the number of items in this menu.

For android.view.View
Boolean View.isGone()

Returns true when this view's visibility is View.GONE, false otherwise.

Boolean View.isInvisible()

Returns true when this view's visibility is View.INVISIBLE, false otherwise.

Boolean View.isVisible()

Returns true when this view's visibility is View.VISIBLE, false otherwise.

Int View.marginBottom()

Returns the bottom margin if this view's LayoutParams is a ViewGroup.MarginLayoutParams, otherwise 0.

Int View.marginEnd()

Returns the end margin if this view's LayoutParams is a ViewGroup.MarginLayoutParams, otherwise 0.

Int View.marginLeft()

Returns the left margin if this view's LayoutParams is a ViewGroup.MarginLayoutParams, otherwise 0.

Int View.marginRight()

Returns the right margin if this view's LayoutParams is a ViewGroup.MarginLayoutParams, otherwise 0.

Int View.marginStart()

Returns the start margin if this view's LayoutParams is a ViewGroup.MarginLayoutParams, otherwise 0.

Int View.marginTop()

Returns the top margin if this view's LayoutParams is a ViewGroup.MarginLayoutParams, otherwise 0.

For android.view.ViewGroup
Sequence<View> ViewGroup.children()

Returns a Sequence over the child views in this view group.

Int ViewGroup.size()

Returns the number of views in this view group.

androidx.core.widget

Dependency

Groovy

dependencies {
    implementation "androidx.core:core-ktx:1.12.0"
}

Kotlin

dependencies {
    implementation("androidx.core:core-ktx:1.12.0")
}

Extension functions

For android.widget.TextView
TextWatcher TextView.addTextChangedListener(crossinline beforeTextChanged: (text: CharSequence?, start: Int, count: Int, after: Int) -> Unit = { _, _, _, _ -> }, crossinline onTextChanged: (text: CharSequence?, start: Int, count: Int, after: Int) -> Unit = { _, _, _, _ -> }, crossinline afterTextChanged: (text: Editable?) -> Unit = {})

Add a text changed listener to this TextView using the provided actions

TextWatcher TextView.doAfterTextChanged(crossinline action: (text: Editable?) -> Unit)

Add an action which will be invoked after the text changed.

TextWatcher TextView.doBeforeTextChanged(crossinline action: (text: CharSequence?, start: Int, count: Int, after: Int) -> Unit)

Add an action which will be invoked before the text changed.

TextWatcher TextView.doOnTextChanged(crossinline action: (text: CharSequence?, start: Int, count: Int, after: Int) -> Unit)

Add an action which will be invoked when the text is changing.

androidx.dynamicanimation.animation

Dependency

Groovy

dependencies {
    implementation "androidx.dynamicanimation:dynamicanimation-ktx:1.1.0-alpha03"
}

Kotlin

dependencies {
    implementation("androidx.dynamicanimation:dynamicanimation-ktx:1.1.0-alpha03")
}

Extension functions

For SpringAnimation
SpringAnimation SpringAnimation.withSpringForceProperties(func: SpringForce.() -> Unit)

Updates or applies spring force properties like SpringForce.mDampingRatio, SpringForce.mFinalPosition and stiffness on SpringAnimation.

Top-level functions

FlingAnimation flingAnimationOf(setter: (Float) -> Unit, getter: () -> Float)

Creates FlingAnimation for a property that can be accessed via the provided setter and getter.

SpringAnimation springAnimationOf(setter: (Float) -> Unit, getter: () -> Float, finalPosition: Float = Float.NaN)

Creates SpringAnimation for a property that can be accessed via the provided setter and getter.

androidx.fragment.app

Dependency

Groovy

dependencies {
    implementation "androidx.fragment:fragment-ktx:1.6.2"
}

Kotlin

dependencies {
    implementation("androidx.fragment:fragment-ktx:1.6.2")
}

Extension functions

For android.view.View
F View.findFragment()

Find a Fragment associated with a View.

For Fragment
Lazy<VM> Fragment.activityViewModels(noinline factoryProducer: () -> ViewModelProvider.Factory = null)

Returns a property delegate to access parent activity's ViewModel, if factoryProducer is specified then ViewModelProvider.Factory returned by it will be used to create ViewModel first time.

Lazy<VM> Fragment.createViewModelLazy(viewModelClass: KClass<VM>, storeProducer: () -> ViewModelStore, factoryProducer: () -> ViewModelProvider.Factory = null)

Helper method for creation of ViewModelLazy, that resolves null passed as factoryProducer to default factory.

Lazy<VM> Fragment.viewModels(noinline ownerProducer: () -> ViewModelStoreOwner = { this }, noinline factoryProducer: () -> ViewModelProvider.Factory = null)

Returns a property delegate to access ViewModel by default scoped to this Fragment:

For FragmentTransaction
FragmentTransaction FragmentTransaction.add(@IdRes containerViewId: Int, tag: String? = null, args: Bundle? = null)

Add a fragment to the associated FragmentManager, inflating the Fragment's view into the container view specified by containerViewId, to later retrieve via FragmentManager.findFragmentById.

FragmentTransaction FragmentTransaction.add(tag: String, args: Bundle? = null)

Add a fragment to the associated FragmentManager without adding the Fragment to any container view.

FragmentTransaction FragmentTransaction.replace(@IdRes containerViewId: Int, tag: String? = null, args: Bundle? = null)

Replace an existing fragment that was added to a container.

For FragmentManager
Unit FragmentManager.commit(allowStateLoss: Boolean = false, body: FragmentTransaction.() -> Unit)

Run body in a FragmentTransaction which is automatically committed if it completes without exception.

Unit FragmentManager.commitNow(allowStateLoss: Boolean = false, body: FragmentTransaction.() -> Unit)

Run body in a FragmentTransaction which is automatically committed if it completes without exception.

Unit FragmentManager.transaction(now: Boolean = false, allowStateLoss: Boolean = false, body: FragmentTransaction.() -> Unit)

Run body in a FragmentTransaction which is automatically committed if it completes without exception.

androidx.fragment.app.testing

Dependency

Groovy

dependencies {
    implementation "androidx.fragment:fragment-testing:1.6.2"
}

Kotlin

dependencies {
    implementation("androidx.fragment:fragment-testing:1.6.2")
}

Top-level functions

FragmentScenario<F!> launchFragment(fragmentArgs: Bundle? = null, @StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme, factory: FragmentFactory? = null)

Launches a Fragment with given arguments hosted by an empty FragmentActivity using given FragmentFactory and waits for it to reach a resumed state.

FragmentScenario<F!> launchFragment(fragmentArgs: Bundle? = null, @StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme, crossinline instantiate: () -> F)

Launches a Fragment with given arguments hosted by an empty FragmentActivity using instantiate to create the Fragment and waits for it to reach a resumed state.

FragmentScenario<F!> launchFragmentInContainer(fragmentArgs: Bundle? = null, @StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme, factory: FragmentFactory? = null)

Launches a Fragment in the Activity's root view container android.R.id.content, with given arguments hosted by an empty FragmentActivity and waits for it to reach a resumed state.

FragmentScenario<F!> launchFragmentInContainer(fragmentArgs: Bundle? = null, @StyleRes themeResId: Int = R.style.FragmentScenarioEmptyFragmentActivityTheme, crossinline instantiate: () -> F)

Launches a Fragment in the Activity's root view container android.R.id.content, with given arguments hosted by an empty FragmentActivity using instantiate to create the Fragment and waits for it to reach a resumed state.

androidx.lifecycle

Dependency

Groovy

dependencies {
    implementation "androidx.lifecycle:lifecycle-livedata-core-ktx:2.7.0"
    implementation "androidx.lifecycle:lifecycle-livedata-ktx:2.7.0"
    implementation "androidx.lifecycle:lifecycle-reactivestreams-ktx:2.7.0"
    implementation "androidx.lifecycle:lifecycle-runtime-ktx:2.7.0"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.7.0"
}

Kotlin

dependencies {
    implementation("androidx.lifecycle:lifecycle-livedata-core-ktx:2.7.0")
    implementation("androidx.lifecycle:lifecycle-livedata-ktx:2.7.0")
    implementation("androidx.lifecycle:lifecycle-reactivestreams-ktx:2.7.0")
    implementation("androidx.lifecycle:lifecycle-runtime-ktx:2.7.0")
    implementation("androidx.lifecycle:lifecycle-viewmodel-ktx:2.7.0")
}

Extension functions

For kotlinx.coroutines.flow.Flow
LiveData<T> Flow<T>.asLiveData(context: CoroutineContext = EmptyCoroutineContext, timeoutInMs: Long = DEFAULT_TIMEOUT)

Creates a LiveData that has values collected from the origin Flow.

LiveData<T> Flow<T>.asLiveData(context: CoroutineContext = EmptyCoroutineContext, timeout: Duration)

Creates a LiveData that has values collected from the origin Flow.

For org.reactivestreams.Publisher
LiveData<T> Publisher<T>.toLiveData()

Creates an observable LiveData stream from a ReactiveStreams Publisher.

For LiveData
Flow<T> LiveData<T>.asFlow()

Creates a Flow containing values dispatched by originating LiveData: at the start a flow collector receives the latest value held by LiveData and then observes LiveData updates.

LiveData<X> LiveData<X>.distinctUntilChanged()

Creates a new LiveData object does not emit a value until the source this LiveData value has been changed.

LiveData<Y> LiveData<X>.map(crossinline transform: (X) -> Y)

Returns a LiveData mapped from this LiveData by applying transform to each value set on this LiveData.

Observer<T> LiveData<T>.observe(owner: LifecycleOwner, crossinline onChanged: (T) -> Unit)

Adds the given onChanged lambda as an observer within the lifespan of the given owner and returns a reference to observer.

LiveData<Y> LiveData<X>.switchMap(crossinline transform: (X) -> LiveData<Y>)

Returns a LiveData mapped from the input this LiveData by applying transform to each value set on this.

Publisher<T> LiveData<T>.toPublisher(lifecycle: LifecycleOwner)

Adapts the given LiveData stream to a ReactiveStreams Publisher.

For ViewModelProvider
VM ViewModelProvider.get()

Returns an existing ViewModel or creates a new one in the scope (usually, a fragment or an activity), associated with this ViewModelProvider.

For LifecycleOwner
suspend T LifecycleOwner.whenCreated(block: suspend CoroutineScope.() -> T)

Runs the given block when the LifecycleOwner's Lifecycle is at least in Lifecycle.State.CREATED state.

suspend T LifecycleOwner.whenResumed(block: suspend CoroutineScope.() -> T)

Runs the given block when the LifecycleOwner's Lifecycle is at least in Lifecycle.State.RESUMED state.

suspend T LifecycleOwner.whenStarted(block: suspend CoroutineScope.() -> T)

Runs the given block when the LifecycleOwner's Lifecycle is at least in Lifecycle.State.STARTED state.

For Lifecycle
suspend T Lifecycle.whenCreated(block: suspend CoroutineScope.() -> T)

Runs the given block when the Lifecycle is at least in Lifecycle.State.CREATED state.

suspend T Lifecycle.whenResumed(block: suspend CoroutineScope.() -> T)

Runs the given block when the Lifecycle is at least in Lifecycle.State.RESUMED state.

suspend T Lifecycle.whenStarted(block: suspend CoroutineScope.() -> T)

Runs the given block when the Lifecycle is at least in Lifecycle.State.STARTED state.

suspend T Lifecycle.whenStateAtLeast(minState: Lifecycle.State, block: suspend CoroutineScope.() -> T)

Runs the given block on a CoroutineDispatcher that executes the block on the main thread and suspends the execution unless the Lifecycle's state is at least minState.

Extension properties

For Lifecycle
LifecycleCoroutineScope Lifecycle.coroutineScope()

CoroutineScope tied to this Lifecycle.

For LifecycleOwner
LifecycleCoroutineScope LifecycleOwner.lifecycleScope()

CoroutineScope tied to this LifecycleOwner's Lifecycle.

For ViewModel
CoroutineScope ViewModel.viewModelScope()

CoroutineScope tied to this ViewModel.

Top-level functions

LiveData<T> liveData(context: CoroutineContext = EmptyCoroutineContext, timeoutInMs: Long = DEFAULT_TIMEOUT, block: suspend LiveDataScope<T>.() -> Unit)

Builds a LiveData that has values yielded from the given block that executes on a LiveDataScope.

LiveData<T> liveData(context: CoroutineContext = EmptyCoroutineContext, timeout: Duration, block: suspend LiveDataScope<T>.() -> Unit)

Builds a LiveData that has values yielded from the given block that executes on a LiveDataScope.

androidx.navigation

Dependency

Groovy

dependencies {
    implementation "androidx.navigation:navigation-runtime-ktx:2.7.7"
    implementation "androidx.navigation:navigation-fragment-ktx:2.7.7"
    implementation "androidx.navigation:navigation-ui-ktx:2.7.7"
}

Kotlin

dependencies {
    implementation("androidx.navigation:navigation-runtime-ktx:2.7.7")
    implementation("androidx.navigation:navigation-fragment-ktx:2.7.7")
    implementation("androidx.navigation:navigation-ui-ktx:2.7.7")
}

Extension functions

For android.app.Activity
NavController Activity.findNavController(@IdRes viewId: Int)

Find a NavController given the id of a View and its containing Activity.

NavArgsLazy<Args> Activity.navArgs()

Returns a Lazy delegate to access the Activity's extras as an Args instance.

For android.view.View
NavController View.findNavController()

Find a NavController associated with a View.

For NavGraphBuilder
Unit NavGraphBuilder.activity(@IdRes id: Int, builder: ActivityNavigatorDestinationBuilder.() -> Unit)

Construct a new ActivityNavigator.Destination

Unit NavGraphBuilder.navigation(@IdRes id: Int, @IdRes startDestination: Int, builder: NavGraphBuilder.() -> Unit)

Construct a nested NavGraph

For NavGraph
operator Boolean NavGraph.contains(@IdRes id: Int)

Returns true if a destination with id is found in this navigation graph.

operator NavDestination NavGraph.get(@IdRes id: Int)

Returns the destination with id.

operator Unit NavGraph.minusAssign(node: NavDestination)

Removes node from this navigation graph.

operator Unit NavGraph.plusAssign(node: NavDestination)

Adds a destination to this NavGraph.

operator Unit NavGraph.plusAssign(other: NavGraph)

Add all destinations from another collection to this one.

For NavController
NavGraph NavController.createGraph(@IdRes id: Int = 0, @IdRes startDestination: Int, builder: NavGraphBuilder.() -> Unit)

Construct a new NavGraph

For NavHost
NavGraph NavHost.createGraph(@IdRes id: Int = 0, @IdRes startDestination: Int, builder: NavGraphBuilder.() -> Unit)

Construct a new NavGraph

For NavigatorProvider
operator T NavigatorProvider.get(name: String)

Retrieves a registered Navigator by name.

operator T NavigatorProvider.get(clazz: KClass<T>)

Retrieves a registered Navigator using the name provided by the Navigator.Name annotation.

NavGraph NavigatorProvider.navigation(@IdRes id: Int = 0, @IdRes startDestination: Int, builder: NavGraphBuilder.() -> Unit)

Construct a new NavGraph

operator Unit NavigatorProvider.plusAssign(navigator: Navigator<out NavDestination>)

Register a navigator using the name provided by the Navigator.Name annotation.

operator Navigator<out NavDestination!>? NavigatorProvider.set(name: String, navigator: Navigator<out NavDestination>)

Register a Navigator by name.

For Fragment
Lazy<VM> Fragment.navGraphViewModels(@IdRes navGraphId: Int, noinline factoryProducer: () -> ViewModelProvider.Factory = null)

Returns a property delegate to access a ViewModel scoped to a navigation graph present on the {@link NavController} back stack:

Top-level functions

ActivityNavigator.Extras ActivityNavigatorExtras(activityOptions: ActivityOptionsCompat? = null, flags: Int = 0)

Create a new ActivityNavigator.Extras instance with a specific ActivityOptionsCompat instance and/or any Intent.FLAG_ACTIVITY_ flags.

NavOptions navOptions(optionsBuilder: NavOptionsBuilder.() -> Unit)

Construct a new NavOptions

androidx.navigation.fragment

Dependency

Groovy

dependencies {
    implementation "androidx.navigation:navigation-fragment-ktx:2.7.7"
}

Kotlin

dependencies {
    implementation("androidx.navigation:navigation-fragment-ktx:2.7.7")
}

Extension functions

For NavGraphBuilder
Unit NavGraphBuilder.dialog(@IdRes id: Int)

Construct a new DialogFragmentNavigator.Destination

Unit NavGraphBuilder.dialog(@IdRes id: Int, builder: DialogFragmentNavigatorDestinationBuilder.() -> Unit)

Construct a new DialogFragmentNavigator.Destination

Unit NavGraphBuilder.fragment(@IdRes id: Int)

Construct a new FragmentNavigator.Destination

Unit NavGraphBuilder.fragment(@IdRes id: Int, builder: FragmentNavigatorDestinationBuilder.() -> Unit)

Construct a new FragmentNavigator.Destination

For Fragment
NavController Fragment.findNavController()

Find a NavController given a Fragment

NavArgsLazy<Args> Fragment.navArgs()

Returns a Lazy delegate to access the Fragment's arguments as an Args instance.

Top-level functions

FragmentNavigator.Extras FragmentNavigatorExtras(vararg sharedElements: Pair<View, String>)

Create a new FragmentNavigator.Extras instance with the given shared elements

androidx.navigation.ui

Dependency

Groovy

dependencies {
    implementation "androidx.navigation:navigation-ui-ktx:2.7.7"
}

Kotlin

dependencies {
    implementation("androidx.navigation:navigation-ui-ktx:2.7.7")
}

Extension functions

For android.view.MenuItem
Boolean MenuItem.onNavDestinationSelected(navController: NavController)

Attempt to navigate to the NavDestination associated with this MenuItem.

For androidx.appcompat.app.AppCompatActivity
Unit AppCompatActivity.setupActionBarWithNavController(navController: NavController, drawerLayout: DrawerLayout?)

Sets up the ActionBar returned by AppCompatActivity.getSupportActionBar for use with a NavController.

Unit AppCompatActivity.setupActionBarWithNavController(navController: NavController, configuration: AppBarConfiguration = AppBarConfiguration(navController.graph))

Sets up the ActionBar returned by AppCompatActivity.getSupportActionBar for use with a NavController.

For androidx.appcompat.widget.Toolbar
Unit Toolbar.setupWithNavController(navController: NavController, drawerLayout: DrawerLayout?)

Sets up a Toolbar for use with a NavController.

Unit Toolbar.setupWithNavController(navController: NavController, configuration: AppBarConfiguration = AppBarConfiguration(navController.graph))

Sets up a Toolbar for use with a NavController.

For com.google.android.material.appbar.CollapsingToolbarLayout
Unit CollapsingToolbarLayout.setupWithNavController(toolbar: Toolbar, navController: NavController, drawerLayout: DrawerLayout?)

Sets up a CollapsingToolbarLayout and Toolbar for use with a NavController.

Unit CollapsingToolbarLayout.setupWithNavController(toolbar: Toolbar, navController: NavController, configuration: AppBarConfiguration = AppBarConfiguration(navController.graph))

Sets up a CollapsingToolbarLayout and Toolbar for use with a NavController.

For com.google.android.material.bottomnavigation.BottomNavigationView
Unit BottomNavigationView.setupWithNavController(navController: NavController)

Sets up a BottomNavigationView for use with a NavController.

For com.google.android.material.navigation.NavigationView
Unit NavigationView.setupWithNavController(navController: NavController)

Sets up a NavigationView for use with a NavController.

For NavController
Boolean NavController.navigateUp(drawerLayout: DrawerLayout?)

Handles the Up button by delegating its behavior to the given NavController.

Boolean NavController.navigateUp(appBarConfiguration: AppBarConfiguration)

Handles the Up button by delegating its behavior to the given NavController.

Top-level functions

AppBarConfiguration AppBarConfiguration(navGraph: NavGraph, drawerLayout: DrawerLayout? = null, noinline fallbackOnNavigateUpListener: () -> Boolean = { false })

Configuration options for NavigationUI methods that interact with implementations of the app bar pattern such as android.support.v7.widget.Toolbar, android.support.design.widget.CollapsingToolbarLayout, and android.support.v7.app.ActionBar.

AppBarConfiguration AppBarConfiguration(topLevelMenu: Menu, drawerLayout: DrawerLayout? = null, noinline fallbackOnNavigateUpListener: () -> Boolean = { false })

Configuration options for NavigationUI methods that interact with implementations of the app bar pattern such as android.support.v7.widget.Toolbar, android.support.design.widget.CollapsingToolbarLayout, and android.support.v7.app.ActionBar.

AppBarConfiguration AppBarConfiguration(topLevelDestinationIds: Set<Int>, drawerLayout: DrawerLayout? = null, noinline fallbackOnNavigateUpListener: () -> Boolean = { false })

Configuration options for NavigationUI methods that interact with implementations of the app bar pattern such as android.support.v7.widget.Toolbar, android.support.design.widget.CollapsingToolbarLayout, and android.support.v7.app.ActionBar.

androidx.paging

Dependency

Groovy

dependencies {
    implementation "androidx.paging:paging-common-ktx:2.1.2"
    implementation "androidx.paging:paging-runtime-ktx:2.1.2"
    implementation "androidx.paging:paging-rxjava2-ktx:2.1.2"
}

Kotlin

dependencies {
    implementation("androidx.paging:paging-common-ktx:2.1.2")
    implementation("androidx.paging:paging-runtime-ktx:2.1.2")
    implementation("androidx.paging:paging-rxjava2-ktx:2.1.2")
}

Extension functions

For Factory
Flowable<PagedList<Value>> DataSource.Factory<Key, Value>.toFlowable(config: PagedList.Config, initialLoadKey: Key? = null, boundaryCallback: PagedList.BoundaryCallback<Value>? = null, fetchScheduler: Scheduler? = null, notifyScheduler: Scheduler? = null, backpressureStrategy: BackpressureStrategy = BackpressureStrategy.LATEST)

Constructs a Flowable<PagedList>, from this DataSource.Factory, convenience for RxPagedListBuilder.

Flowable<PagedList<Value>> DataSource.Factory<Key, Value>.toFlowable(pageSize: Int, initialLoadKey: Key? = null, boundaryCallback: PagedList.BoundaryCallback<Value>? = null, fetchScheduler: Scheduler? = null, notifyScheduler: Scheduler? = null, backpressureStrategy: BackpressureStrategy = BackpressureStrategy.LATEST)

Constructs a Flowable<PagedList>, from this DataSource.Factory, convenience for RxPagedListBuilder.

LiveData<PagedList<Value>> DataSource.Factory<Key, Value>.toLiveData(config: PagedList.Config, initialLoadKey: Key? = null, boundaryCallback: PagedList.BoundaryCallback<Value>? = null, fetchExecutor: Executor = ArchTaskExecutor.getIOThreadExecutor())

Constructs a LiveData<PagedList>, from this DataSource.Factory, convenience for LivePagedListBuilder.

LiveData<PagedList<Value>> DataSource.Factory<Key, Value>.toLiveData(pageSize: Int, initialLoadKey: Key? = null, boundaryCallback: PagedList.BoundaryCallback<Value>? = null, fetchExecutor: Executor = ArchTaskExecutor.getIOThreadExecutor())

Constructs a LiveData<PagedList>, from this DataSource.Factory, convenience for LivePagedListBuilder.

Observable<PagedList<Value>> DataSource.Factory<Key, Value>.toObservable(config: PagedList.Config, initialLoadKey: Key? = null, boundaryCallback: PagedList.BoundaryCallback<Value>? = null, fetchScheduler: Scheduler? = null, notifyScheduler: Scheduler? = null)

Constructs a Observable<PagedList> from this DataSource.Factory, convenience for RxPagedListBuilder.

Observable<PagedList<Value>> DataSource.Factory<Key, Value>.toObservable(pageSize: Int, initialLoadKey: Key? = null, boundaryCallback: PagedList.BoundaryCallback<Value>? = null, fetchScheduler: Scheduler? = null, notifyScheduler: Scheduler? = null)

Constructs a Observable<PagedList> from this DataSource.Factory, convenience for RxPagedListBuilder.

Top-level functions

PagedList.Config Config(pageSize: Int, prefetchDistance: Int = pageSize, enablePlaceholders: Boolean = true, initialLoadSizeHint: Int = pageSize * PagedList.Config.Builder.DEFAULT_INITIAL_PAGE_MULTIPLIER, maxSize: Int = PagedList.Config.MAX_SIZE_UNBOUNDED)

Constructs a PagedList.Config, convenience for PagedList.Config.Builder.

PagedList<Value> PagedList(dataSource: DataSource<Key, Value>, config: PagedList.Config, notifyExecutor: Executor, fetchExecutor: Executor, boundaryCallback: PagedList.BoundaryCallback<Value>? = null, initialKey: Key? = null)

Constructs a PagedList, convenience for PagedList.Builder.

androidx.palette.graphics

Dependency

Groovy

dependencies {
    implementation "androidx.palette:palette-ktx:1.0.0"
}

Kotlin

dependencies {
    implementation("androidx.palette:palette-ktx:1.0.0")
}

Extension functions

For Palette
operator Palette.Swatch? Palette.get(target: Target)

Returns the selected swatch for the given target from the palette, or null if one could not be found.

androidx.preference

Dependency

Groovy

dependencies {
    implementation "androidx.preference:preference-ktx:1.2.1"
}

Kotlin

dependencies {
    implementation("androidx.preference:preference-ktx:1.2.1")
}

Extension functions

For PreferenceGroup
operator Boolean PreferenceGroup.contains(preference: Preference)

Returns true if preference is found in this preference group.

Unit PreferenceGroup.forEach(action: (preference: Preference) -> Unit)

Performs the given action on each preference in this preference group.

Unit PreferenceGroup.forEachIndexed(action: (index: Int, preference: Preference) -> Unit)

Performs the given action on each preference in this preference group, providing its sequential index.

operator T? PreferenceGroup.get(key: CharSequence)

Returns the preference with key, or null if no preference with key is found.

operator Preference PreferenceGroup.get(index: Int)

Returns the preference at index.

Boolean PreferenceGroup.isEmpty()

Returns true if this preference group contains no preferences.

Boolean PreferenceGroup.isNotEmpty()

Returns true if this preference group contains one or more preferences.

operator MutableIterator<Preference> PreferenceGroup.iterator()

Returns a MutableIterator over the preferences in this preference group.

operator Unit PreferenceGroup.minusAssign(preference: Preference)

Removes preference from this preference group.

operator Unit PreferenceGroup.plusAssign(preference: Preference)

Adds preference to this preference group.

Extension properties

For PreferenceGroup
Sequence<Preference> PreferenceGroup.children()

Returns a Sequence over the preferences in this preference group.

Int PreferenceGroup.size()

Returns the number of preferences in this preference group.

androidx.room

Dependency

Groovy

dependencies {
    implementation "androidx.room:room-ktx:2.6.1"
}

Kotlin

dependencies {
    implementation("androidx.room:room-ktx:2.6.1")
}

Extension functions

For RoomDatabase
suspend R RoomDatabase.withTransaction(block: suspend () -> R)

Calls the specified suspending block in a database transaction.

androidx.slice.builders

Dependency

Groovy

dependencies {
    implementation "androidx.slice:slice-builders-ktx:1.0.0-alpha08"
}

Kotlin

dependencies {
    implementation("androidx.slice:slice-builders-ktx:1.0.0-alpha08")
}

Extension functions

For GridRowBuilderDsl
GridRowBuilder GridRowBuilderDsl.cell(buildCell: CellBuilderDsl.() -> Unit)

GridRowBuilder GridRowBuilderDsl.seeMoreCell(buildCell: CellBuilderDsl.() -> Unit)

For ListBuilderDsl
ListBuilder ListBuilderDsl.gridRow(buildGrid: GridRowBuilderDsl.() -> Unit)

ListBuilder ListBuilderDsl.header(buildHeader: HeaderBuilderDsl.() -> Unit)

ListBuilder ListBuilderDsl.inputRange(buildInputRange: InputRangeBuilderDsl.() -> Unit)

ListBuilder ListBuilderDsl.range(buildRange: RangeBuilderDsl.() -> Unit)

ListBuilder ListBuilderDsl.row(buildRow: RowBuilderDsl.() -> Unit)

ListBuilder ListBuilderDsl.seeMoreRow(buildRow: RowBuilderDsl.() -> Unit)

Top-level functions

Slice list(context: Context, uri: Uri, ttl: Long, addRows: ListBuilderDsl.() -> Unit)

Reduces verbosity required to build a Slice in Kotlin.

SliceAction tapSliceAction(pendingIntent: PendingIntent, icon: IconCompat, imageMode: Int = ICON_IMAGE, title: CharSequence)

Factory method to build a tappable SliceAction.

SliceAction toggleSliceAction(pendingIntent: PendingIntent, icon: IconCompat? = null, title: CharSequence, isChecked: Boolean)

Factory method to build a toggleable SliceAction.

androidx.sqlite.db

Dependency

Groovy

dependencies {
    implementation "androidx.sqlite:sqlite-ktx:2.4.0"
}

Kotlin

dependencies {
    implementation("androidx.sqlite:sqlite-ktx:2.4.0")
}

Extension functions

For SupportSQLiteDatabase
T SupportSQLiteDatabase.transaction(exclusive: Boolean = true, body: SupportSQLiteDatabase.() -> T)

Run body in a transaction marking it as successful if it completes without exception.

androidx.work

Dependency

Extension functions

For com.google.common.util.concurrent.ListenableFuture
suspend R ListenableFuture<R>.await()

Awaits for the completion of the ListenableFuture without blocking a thread.

For Operation
suspend Operation.State.SUCCESS! Operation.await()

Awaits an Operation without blocking a thread.

For Data
Boolean Data.hasKeyWithValueOfType(key: String)

Returns true if the instance of Data has a value corresponding to the given key with an expected type T.

For Builder
OneTimeWorkRequest.Builder OneTimeWorkRequest.Builder.setInputMerger(@NonNull inputMerger: KClass<out InputMerger>)

Sets an InputMerger on the OneTimeWorkRequest.Builder.

Top-level functions

OneTimeWorkRequest.Builder OneTimeWorkRequestBuilder()

Creates a OneTimeWorkRequest with the given ListenableWorker.

PeriodicWorkRequest.Builder PeriodicWorkRequestBuilder(repeatInterval: Long, repeatIntervalTimeUnit: TimeUnit)

Creates a PeriodicWorkRequest.Builder with a given ListenableWorker.

PeriodicWorkRequest.Builder PeriodicWorkRequestBuilder(repeatInterval: Duration)

Creates a PeriodicWorkRequest.Builder with a given ListenableWorker.

PeriodicWorkRequest.Builder PeriodicWorkRequestBuilder(repeatInterval: Long, repeatIntervalTimeUnit: TimeUnit, flexTimeInterval: Long, flexTimeIntervalUnit: TimeUnit)

Creates a PeriodicWorkRequest.Builder with a given ListenableWorker.

PeriodicWorkRequest.Builder PeriodicWorkRequestBuilder(repeatInterval: Duration, flexTimeInterval: Duration)

Creates a PeriodicWorkRequest.Builder with a given ListenableWorker.

Data workDataOf(vararg pairs: Pair<String, Any?>)

Converts a list of pairs to a Data object.

androidx.work.testing

Dependency

Groovy

dependencies {
    implementation "androidx.work:work-testing:2.9.0"
}

Kotlin

dependencies {
    implementation("androidx.work:work-testing:2.9.0")
}

Top-level functions

TestListenableWorkerBuilder<W> TestListenableWorkerBuilder(context: Context, inputData: Data = Data.EMPTY, tags: List<String> = emptyList(), runAttemptCount: Int = 1, triggeredContentUris: List<Uri> = emptyList(), triggeredContentAuthorities: List<String> = emptyList())

Builds an instance of TestListenableWorkerBuilder.

TestWorkerBuilder<W> TestWorkerBuilder(context: Context, executor: Executor, inputData: Data = Data.EMPTY, tags: List<String> = emptyList(), runAttemptCount: Int = 1, triggeredContentUris: List<Uri> = emptyList(), triggeredContentAuthorities: List<String> = emptyList())

Builds an instance of TestWorkerBuilder.

com.google.android.play.core.ktx

Dependency

Groovy

dependencies {
    implementation "com.google.android.play:core-ktx:1.8.1"
}

Kotlin

dependencies {
    implementation("com.google.android.play:core-ktx:1.8.1")
}

Extension functions

For com.google.android.play.core.appupdate.AppUpdateManager
suspend AppUpdateInfo AppUpdateManager.requestAppUpdateInfo()

Requests the update availability for the current app

suspend Unit AppUpdateManager.requestCompleteUpdate()

For a flexible update flow, triggers the completion of the update.

Flow<AppUpdateResult> AppUpdateManager.requestUpdateFlow()

Entry point for monitoring the availability and progress of updates.

Boolean AppUpdateManager.startUpdateFlowForResult(appUpdateInfo: AppUpdateInfo, appUpdateType: Int, fragment: Fragment, requestCode: Int)

A version of AppUpdateManager.startUpdateFlowForResult that accepts an AndroidX Fragment for returning the result.

For com.google.android.play.core.splitinstall.SplitInstallManager
suspend Unit SplitInstallManager.requestCancelInstall(sessionId: Int)

Suspend version of SplitInstallManager.cancelInstall

suspend Unit SplitInstallManager.requestDeferredInstall(moduleNames: List<String>)

Suspend version of SplitInstallManager.deferredInstall

suspend Unit SplitInstallManager.requestDeferredLanguageInstall(languages: List<Locale>)

Suspend version of SplitInstallManager.deferredLanguageInstall

suspend Unit SplitInstallManager.requestDeferredLanguageUninstall(languages: List<Locale>)

Suspend version of SplitInstallManager.deferredLanguageUninstall

suspend Unit SplitInstallManager.requestDeferredUninstall(moduleNames: List<String>)

Suspend version of SplitInstallManager.deferredUninstall

suspend Int SplitInstallManager.requestInstall(modules: List<String> = listOf(), languages: List<String> = listOf())

Initiates installation of the requested modules/languages.

Flow<SplitInstallSessionState> SplitInstallManager.requestProgressFlow()

Creates and returns a buffered Flow that will deliver all progress events for ongoing split installations.

suspend SplitInstallSessionState SplitInstallManager.requestSessionState(sessionId: Int)

Suspend version of SplitInstallManager.getSessionState

suspend List<SplitInstallSessionState> SplitInstallManager.requestSessionStates()

Suspend version of SplitInstallManager.getSessionStates

Boolean SplitInstallManager.startConfirmationDialogForResult(sessionState: SplitInstallSessionState, fragment: Fragment, requestCode: Int)

A version of SplitInstallManager.startConfirmationDialogForResult that accepts an AndroidX Fragment for returning the result.

Extension properties

For com.google.android.play.core.appupdate.AppUpdateInfo
Int AppUpdateInfo.installStatus()

Returns the progress status of the update.

Boolean AppUpdateInfo.isFlexibleUpdateAllowed()

Returns true if flexible update is allowed.

Boolean AppUpdateInfo.isImmediateUpdateAllowed()

Returns true if immediate update is allowed.

For com.google.android.play.core.install.InstallState
Boolean InstallState.hasTerminalStatus()

This signifies that this is a terminal status (there will be no more updates) and should be handled accordingly (success, cancellation or failure).

Int InstallState.installErrorCode()

Returns the error code for an install, or {@link InstallErrorCode#NO_ERROR}.

Int InstallState.installStatus()

Returns the status of an install.

String! InstallState.packageName()

Returns the package name for the app being installed.

For com.google.android.play.core.splitinstall.SplitInstallSessionState
Long SplitInstallSessionState.bytesDownloaded()

The bytes downloaded by this update.

Int SplitInstallSessionState.errorCode()

The error code of this update.

Boolean SplitInstallSessionState.hasTerminalStatus()

Signifies that this update is terminal, meaning there will be no more updates for this session.

List<String> SplitInstallSessionState.languages()

The languages included by this update.

List<String> SplitInstallSessionState.moduleNames()

The modules included by this update.

Int SplitInstallSessionState.sessionId()

The session id of this update.

Int SplitInstallSessionState.status()

The status code of this update.

Long SplitInstallSessionState.totalBytesToDownload()

The total bytes to download by this update.

Top-level functions

SplitInstallStateUpdatedListener SplitInstallStateUpdatedListener(onRequiresConfirmation: (SplitInstallSessionState) -> Unit, onInstalled: (SplitInstallSessionState) -> Unit, onFailed: (SplitInstallSessionState) -> Unit = {}, onPending: (SplitInstallSessionState) -> Unit = {}, onDownloaded: (SplitInstallSessionState) -> Unit = {}, onDownloading: (SplitInstallSessionState) -> Unit = {}, onInstalling: (SplitInstallSessionState) -> Unit = {}, onCanceling: (SplitInstallSessionState) -> Unit = {}, onCanceled: (SplitInstallSessionState) -> Unit = {}, onNonTerminalStatus: (SplitInstallSessionState) -> Unit = {}, onTerminalStatus: (SplitInstallSessionState) -> Unit = {})

A convenience function for creating a SplitInstallStateUpdatedListener.