常用的一些扩展函数整理
项目中用到的一些常用的扩展函数的整理,在很多的地方用起来都很方便,然后也做了一下整理。分享一下
先来一个 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()
}
})
}
还遇到了什么以后在加在总结!!!