Android kotlin常用的一些扩展函数整理

常用的一些扩展函数整理

项目中用到的一些常用的扩展函数的整理,在很多的地方用起来都很方便,然后也做了一下整理。分享一下

先来一个 dp px sp 直接的转换

/**
 * px转dp
 */
fun Context.px2dip(px: Float): Float = px / resources.displayMetrics.density + 0.5f
fun Context.px2dip(px: Int): Int = px2dip(px.toFloat()).toInt()

/**
 * dp转px
 */
fun Context.dip2px(dp: Float): Float = applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,
    dp,
    resources.displayMetrics
)

fun Context.dip2px(dp: Int): Int = applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,
    dp.toFloat(),
    resources.displayMetrics
).toInt()

/**
 * sp转px
 */
fun Context.sp2px(sp: Float): Float = applyDimension(
    TypedValue.COMPLEX_UNIT_SP,
    sp,
    resources.displayMetrics
)

fun Context.sp2px(sp: Int): Int = applyDimension(
    TypedValue.COMPLEX_UNIT_SP,
    sp.toFloat(),
    resources.displayMetrics
).toInt()

toast相关

/**
 * toast
 */
fun Context.toast(msg: CharSequence, duration: Int = Toast.LENGTH_SHORT) =
    Toast.makeText(this, msg, duration).show()

fun Context.toast(resId: Int, duration: Int = Toast.LENGTH_SHORT) =
    Toast.makeText(this, resId, duration).show()

获取状态栏的高度

/**
 * 状态栏的高度
 */
inline val Context.statusBarHeight: Int
    get() {
        var result = 0
        val resourceId = resources.getIdentifier("status_bar_height", "dimen", "android")
        if (resourceId > 0) {
            result = runCatching { resources.getDimensionPixelSize(resourceId) }.getOrDefault(0)
        }

        if (result == 0) {
            result = dip2px(24)
        }
        return result
    }

获取屏幕的宽度高度

/**
 * 获取屏幕的宽度和高度
 */
val Context.screesSize: Point
    get() {
        val p = Point()
        val wm = getSystemService<WindowManager>() ?: return p
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            val bounds = wm.currentWindowMetrics.bounds
            p.x = bounds.width()
            p.y = bounds.height()
        } else {
            @Suppress("DEPRECATION")
            wm.defaultDisplay?.getRealSize(p)
        }
        return p
    }

获取版本相关

/**
 * 获取app版本号的code V1.0.0
 */
inline val Context.versionCode
    get() = try {
        this.packageManager.getPackageInfo(this.packageName, 0).getVersionCode()
    } catch (e: Exception) {
        0L
    }

/**
 * 获取app版本号的名称
 */
@Suppress("HasPlatformType")
inline val Context.versionName
    get() = try {
        this.packageManager.getPackageInfo(this.packageName, 0).versionName
    } catch (e: Exception) {
        "unknown"
    }


@Suppress("DEPRECATION")
@SuppressLint("NewApi")
fun PackageInfo.getVersionCode(): Long {
    return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) this.longVersionCode else this.versionCode.toLong()
}

设置字体颜色

/**
 * 设置字体的颜色
 */
inline fun <reified T: TextView> T.setTextColorResource(@ColorRes id: Int): T {
    this.setTextColor(this.context.getColorResource(id))
    return this
}

inline fun <reified T: TextView> T.setTextColorResource(context: Context, @ColorRes id: Int): T {
    this.setTextColor(context.getColorResource(id))
    return this
}

控件加载完成

/**
 * 控件加载完成
 */
inline fun View.onGlobalLayout(crossinline callback: () -> Unit) {
    this.viewTreeObserver.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener {
        @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
        override fun onGlobalLayout() {
            viewTreeObserver.removeOnGlobalLayoutListener(this)
            callback()
        }
    })
}

还遇到了什么以后在加在总结!!!

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值