Android Core KTX汇总(一)

381 阅读10分钟

animation

animation包下关注的是动画相关的KTX

Animator

Animator.addListener

  • 作用:向Animator添加AnimatorListener并返回该AnimatorListener。

  • 意义:按需实现对应动作的回调操作,无需实现所有动作的回调。

  • 实现:方法内部创建AnimatorListener的匿名对象,并将对应动作的回调与传入的操作连接起来。传入的操作默认都为空实现,所以无需传入所有操作。

  • 代码:

    public inline fun Animator.addListener(
        crossinline onEnd: (animator: Animator) -> Unit = {},
        crossinline onStart: (animator: Animator) -> Unit = {},
        crossinline onCancel: (animator: Animator) -> Unit = {},
        crossinline onRepeat: (animator: Animator) -> Unit = {}
    ): Animator.AnimatorListener {
        val listener = object : Animator.AnimatorListener {
            override fun onAnimationRepeat(animator: Animator) = onRepeat(animator)
            override fun onAnimationEnd(animator: Animator) = onEnd(animator)
            override fun onAnimationCancel(animator: Animator) = onCancel(animator)
            override fun onAnimationStart(animator: Animator) = onStart(animator)
        }
        addListener(listener)
        return listener
    }
    

Animator.addPauseListener

  • 作用:向Animator添加AnimatorPauseListener并返回该AnimatorPauseListener。

  • 意义:同addListener。

  • 实现:类似addListener。

  • 代码:

    @RequiresApi(19)
    public inline fun Animator.addPauseListener(
        crossinline onResume: (animator: Animator) -> Unit = {},
        crossinline onPause: (animator: Animator) -> Unit = {}
    ): Animator.AnimatorPauseListener {
        val listener = object : Animator.AnimatorPauseListener {
            override fun onAnimationPause(animator: Animator) = onPause(animator)
            override fun onAnimationResume(animator: Animator) = onResume(animator)
        }
        addPauseListener(listener)
        return listener
    }
    

Animator.doOnCancel

  • 作用:监听Animator的取消回调。

  • 意义:只需实现指定回调的操作,无需实现其他回调操作。

  • 实现:调用addListener并只传入onCancel。

  • 注意:因为每一个doOnXXX的方法都会创建一个新的Listener对象,所以当且仅当只需要该回调时使用。

  • 代码:

    public inline fun Animator.doOnCancel(
        crossinline action: (animator: Animator) -> Unit
    ): Animator.AnimatorListener =
        addListener(onCancel = action)
    

Animator.doOnEnd

  • 作用:监听Animator的结束回调。

  • 意义:只需实现指定回调的操作,无需实现其他回调操作。

  • 实现:调用addListener并只传入onEnd。

  • 注意:因为每一个doOnXXX的方法都会创建一个新的Listener对象,所以当且仅当只需要该回调时使用。

  • 代码:

    public inline fun Animator.doOnEnd(
        crossinline action: (animator: Animator) -> Unit
    ): Animator.AnimatorListener =
        addListener(onEnd = action)
    

Animator.doOnPause

  • 作用:监听Animator的暂停回调。

  • 意义:只需实现指定回调的操作,无需实现其他回调操作。

  • 实现:调用addListener并只传入onPause。

  • 注意:因为每一个doOnXXX的方法都会创建一个新的Listener对象,所以当且仅当只需要该回调时使用。

  • 代码:

    public inline fun Animator.doOnPause(
        crossinline action: (animator: Animator) -> Unit
    ): Animator.AnimatorListener =
        addListener(onPause = action)
    

Animator.doOnRepeat

  • 作用:监听Animator的重放回调。

  • 意义:只需实现指定回调的操作,无需实现其他回调操作。

  • 实现:调用addListener并只传入onRepeat。

  • 注意:因为每一个doOnXXX的方法都会创建一个新的Listener对象,所以当且仅当只需要该回调时使用。

  • 代码:

    public inline fun Animator.doOnRepeat(
        crossinline action: (animator: Animator) -> Unit
    ): Animator.AnimatorListener =
        addListener(onRepeat = action)
    

Animator.doOnResume

  • 作用:监听Animator的恢复回调。

  • 意义:只需实现指定回调的操作,无需实现其他回调操作。

  • 实现:调用addListener并只传入onResume。

  • 注意:因为每一个doOnXXX的方法都会创建一个新的Listener对象,所以当且仅当只需要该回调时使用。

  • 代码:

    public inline fun Animator.doOnResume(
        crossinline action: (animator: Animator) -> Unit
    ): Animator.AnimatorListener =
        addListener(onResume = action)
    

Animator.doOnStart

  • 作用:监听Animator的开始回调。

  • 意义:只需实现指定回调的操作,无需实现其他回调操作。

  • 实现:调用addListener并只传入onStart。

  • 注意:因为每一个doOnXXX的方法都会创建一个新的Listener对象,所以当且仅当只需要该回调时使用。

  • 代码:

    public inline fun Animator.doOnStart(
        crossinline action: (animator: Animator) -> Unit
    ): Animator.AnimatorListener =
        addListener(onStart = action)
    

content

content包下关注的是ContentValue、Context、SharedPreferences相关的KTX

ContentValue

contentValueOf

  • 作用:将若干个Pair<String,Any?>构建出ContentValue。

  • 意义:便捷地构建ContentValue,无需根据不同类型的数据手动调用不同的put方法。

  • 实现:根据传入的Pair数量初始化ContentValue,并遍历Pair,判断second的类型调用不同的put方法。

  • 代码:

    public fun contentValuesOf(
        vararg pairs: Pair<String, Any?>
    ): ContentValues = ContentValues(pairs.size).apply {
        for ((key, value) in pairs) {
            when (value) {
                null -> putNull(key)
                is String -> put(key, value)
                is Int -> put(key, value)
                is Long -> put(key, value)
                is Boolean -> put(key, value)
                is Float -> put(key, value)
                is Double -> put(key, value)
                is ByteArray -> put(key, value)
                is Byte -> put(key, value)
                is Short -> put(key, value)
                else -> {
                    val valueType = value.javaClass.canonicalName
                    throw IllegalArgumentException("Illegal value type $valueType for key "$key"")
                }
            }
        }
    }
    

Context

Context.getSystemService

  • 作用:获取系统服务

  • 意义:可通过指定泛型或者类型推断获取系统服务,无需传入name。

  • 实现:通过泛型获取class,调用ContextCompat.getSystemService获取对应系统服务。

  • 代码:

    public inline fun <reified T : Any> Context.getSystemService(): T? =
        ContextCompat.getSystemService(this, T::class.java)
    

withStyledAttributes

  • 作用:获取TypedArray后,以TypedArray作为Receiver调用一段代码,最后自动recycle。

  • 意义:简化在View的初始化时获取TypedArray并进行处理的逻辑。

  • 实现:调用obtainStyledAttributes获取TypedArray,调用apply运行block,最后调用recycle。

  • 代码:

    public inline fun Context.withStyledAttributes(
        set: AttributeSet? = null,
        attrs: IntArray,
        @AttrRes defStyleAttr: Int = 0,
        @StyleRes defStyleRes: Int = 0,
        block: TypedArray.() -> Unit
    ) {
        obtainStyledAttributes(set, attrs, defStyleAttr, defStyleRes).apply(block).recycle()
    }
    

withStyledAttributes

此方法为重载方法,适配obtainStyledAttributes的重载方法。

  • 代码:

    public inline fun Context.withStyledAttributes(
        @StyleRes resourceId: Int,
        attrs: IntArray,
        block: TypedArray.() -> Unit
    ) {
        obtainStyledAttributes(resourceId, attrs).apply(block).recycle()
    }
    

SharedPreferences

edit

  • 作用:打开Editor作用域并自动commit或apply(通过commit参数配置,默认为false,即默认使用apply)。

  • 意义:直接在Editor中调用putXXX,省去重复的"editor."的写法。自动commit(apply),杜绝人为遗漏的问题。

  • 实现:先调用edit()获取Editor,并以Editor为receiver调用action,最后根据commit参数判断调用commit()或apply()。

  • 代码:

    public inline fun SharedPreferences.edit(
        commit: Boolean = false,
        action: SharedPreferences.Editor.() -> Unit
    ) {
        val editor = edit()
        action(editor)
        if (commit) {
            editor.commit()
        } else {
            editor.apply()
        }
    }
    

TypedArray

TypedArray.getBooleanOrThrow

  • 作用:获取处于index的已定义属性的布尔值,默认为false,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getBoolean之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    public fun TypedArray.getBooleanOrThrow(@StyleableRes index: Int): Boolean {
        checkAttribute(index)
        return getBoolean(index, false)
    }
    

TypedArray.getColorOrThrow

  • 作用:获取处于index的已定义属性的Color值,默认为0,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getColor之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    @ColorInt
    public fun TypedArray.getColorOrThrow(@StyleableRes index: Int): Int {
        checkAttribute(index)
        return getColor(index, 0)
    }
    

TypedArray.getColorStateListOrThrow

  • 作用:获取处于index的已定义属性的ColorStateList值,获取为空则抛出IllegalStateException异常,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getColorStateList之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    public fun TypedArray.getColorStateListOrThrow(@StyleableRes index: Int): ColorStateList {
        checkAttribute(index)
        return checkNotNull(getColorStateList(index)) {
            "Attribute value was not a color or color state list."
        }
    }
    

TypedArray.getDimensionOrThrow

  • 作用:获取处于index的已定义属性的Dimension值,默认为0,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getDimension之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    public fun TypedArray.getDimensionOrThrow(@StyleableRes index: Int): Float {
        checkAttribute(index)
        return getDimension(index, 0f)
    }
    

TypedArray.getDimensionPixelOffsetOrThrow

  • 作用:获取处于index的已定义属性的DimensionPixelOffset值,默认为0,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getDimensionPixelOffset之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    @Dimension
    public fun TypedArray.getDimensionPixelOffsetOrThrow(@StyleableRes index: Int): Int {
        checkAttribute(index)
        return getDimensionPixelOffset(index, 0)
    }
    

TypedArray.getDimensionPixelSizeOrThrow

  • 作用:获取处于index的已定义属性的DimensionPixelSize值,默认为0,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getDimensionPixelSize之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    @Dimension
    public fun TypedArray.getDimensionPixelSizeOrThrow(@StyleableRes index: Int): Int {
        checkAttribute(index)
        return getDimensionPixelSize(index, 0)
    }
    

TypedArray.getDrawableOrThrow

  • 作用:获取处于index的已定义属性的Drawable,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getBoolean之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    public fun TypedArray.getDrawableOrThrow(@StyleableRes index: Int): Drawable {
        checkAttribute(index)
        return getDrawable(index)!!
    }
    

TypedArray.getFloatOrThrow

  • 作用:获取处于index的已定义属性的float值,默认为0,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getFloat之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    public fun TypedArray.getFloatOrThrow(@StyleableRes index: Int): Float {
        checkAttribute(index)
        return getFloat(index, 0f)
    }
    

TypedArray.getFontOrThrow

  • 作用:获取处于index的已定义属性的Font值,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getBoolean之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    @RequiresApi(26)
    public fun TypedArray.getFontOrThrow(@StyleableRes index: Int): Typeface {
        checkAttribute(index)
        return getFont(index)!!
    }
    

TypedArray.getIntOrThrow

  • 作用:获取处于index的已定义属性的int值,默认为0,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getInt之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    public fun TypedArray.getIntOrThrow(@StyleableRes index: Int): Int {
        checkAttribute(index)
        return getInt(index, 0)
    }
    

TypedArray.getIntegerOrThrow

  • 作用:获取处于index的已定义属性的Integer值,默认为0,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getInteger之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    public fun TypedArray.getIntegerOrThrow(@StyleableRes index: Int): Int {
        checkAttribute(index)
        return getInteger(index, 0)
    }
    

TypedArray.getResourceIdOrThrow

  • 作用:获取处于index的已定义属性的ResourceId值,默认为0,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getResourceId之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    @AnyRes
    public fun TypedArray.getResourceIdOrThrow(@StyleableRes index: Int): Int {
        checkAttribute(index)
        return getResourceId(index, 0)
    }
    

TypedArray.getStringOrThrow

  • 作用:获取处于index的已定义属性的String,获取为空则抛出IllegalStateException异常,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getString之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    public fun TypedArray.getBooleanOrThrow(@StyleableRes index: Int): Boolean {
        checkAttribute(index)
        return getBoolean(index, false)
    }
    

TypedArray.getTextOrThrow

  • 作用:获取处于index的已定义属性的CharSequence值,获取为空则抛出IllegalStateException异常,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getText之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    public fun TypedArray.getTextOrThrow(@StyleableRes index: Int): CharSequence {
        checkAttribute(index)
        return checkNotNull(getText(index)) {
            "Attribute value could not be coerced to CharSequence."
        }
    }
    

TypedArray.getTextArrayOrThrow

  • 作用:获取处于index的已定义属性的TextArray,未定义则抛出IllegalArgumentException异常。

  • 意义:简化TypedArray的使用。

  • 实现:返回getTextArray之前调用checkAttribute。checkAttribute使用hasValue判断是否已定义该index的属性,未定义则抛出异常。

  • 代码:

    public fun TypedArray.getTextArrayOrThrow(@StyleableRes index: Int): Array<CharSequence> {
        checkAttribute(index)
        return getTextArray(index)
    }
    

TypedArray.use

  • 作用:执行了block代码块后调用recycle。

  • 意义:杜绝人为忘记recycle的情况。

  • 实现:执行block后自动调用recycle。

  • 代码:

    public inline fun <R> TypedArray.use(block: (TypedArray) -> R): R {
        return block(this).also {
            recycle()
        }
    }
    

database

database包下是与sqlite相关的KTX

SQLiteDatabase

SQLiteDatabase.transaction

  • 作用:自动开启一个transaction,运行body后,自动结束transaction。

  • 意义:使用者只需关注执行的内容即可。

  • 实现:根据参数开启transaction,并在finally中结束transaction。

  • 代码:

    public inline fun <T> SQLiteDatabase.transaction(
        exclusive: Boolean = true,
        body: SQLiteDatabase.() -> T
    ): T {
        if (exclusive) {
            beginTransaction()
        } else {
            beginTransactionNonExclusive()
        }
        try {
            val result = body()
            setTransactionSuccessful()
            return result
        } finally {
            endTransaction()
        }
    }
    

Cursor

Cursor.getBlobOrNull

  • 作用:获取位于index的blob,没有则返回null

  • 代码:

    public inline fun Cursor.getBlobOrNull(
        index: Int
    ): ByteArray? = if (isNull(index)) null else getBlob(index)
    

Cursor.getDoubleOrNull

  • 作用:获取位于index的Double,没有则返回null

  • 代码:

    public inline fun Cursor.getDoubleOrNull(
        index: Int
    ): Double? = if (isNull(index)) null else getDouble(index)
    

Cursor.getFloatOrNull

  • 作用:获取位于index的float,没有则返回null

  • 代码:

    public inline fun Cursor.getFloatOrNull(
        index: Int
    ): Float? = if (isNull(index)) null else getFloat(index)
    

Cursor.getIntOrNull

  • 作用:获取位于index的int,没有则返回null

  • 代码:

    public inline fun Cursor.getIntOrNull(
        index: Int
    ): Int? = if (isNull(index)) null else getInt(index)
    

Cursor.getLongOrNull

  • 作用:获取位于index的Long,没有则返回null

  • 代码:

    public inline fun Cursor.getLongOrNull(
        index: Int
    ): Long? = if (isNull(index)) null else getLong(index)
    

Cursor.getShortOrNull

  • 作用:获取位于index的short,没有则返回null

  • 代码:

    public inline fun Cursor.getShortOrNull(
        index: Int
    ): Short? = if (isNull(index)) null else getShort(index)
    

Cursor.getStringOrNull

  • 作用:获取位于index的String,没有则返回null

  • 代码:

    public inline fun Cursor.getStringOrNull(
        index: Int
    ): String? = if (isNull(index)) null else getString(index)
    

\