美文网首页
Activity、Fragment扩展方法Kotlin

Activity、Fragment扩展方法Kotlin

作者: 狼狗猫 | 来源:发表于2020-01-08 17:39 被阅读0次

获取颜色

fun FragmentActivity.color( res: Int): Int {
    return ContextCompat.getColor(baseContext, res)
}
fun Fragment.color(@ColorRes res: Int): Int {
    return ContextCompat.getColor(requireContext(), res)
}

fun Context.color(@ColorRes res: Int): Int {
    return ContextCompat.getColor(this, res)
}

获取宽高

fun FragmentActivity.getWidthPixels(): Int {
    return resources.displayMetrics.widthPixels
}

fun Context.getWidthPixels(): Int {
    return resources.displayMetrics.widthPixels
}
fun FragmentActivity.getHeightPixels(): Int {
    return resources.displayMetrics.heightPixels
}

toast中心位置

fun FragmentActivity.toastCenter(message: CharSequence): Toast =
    Toast.makeText(this, message, Toast.LENGTH_SHORT).apply {
        setGravity(Gravity.CENTER, 0, 0)
        show()
    }


fun Fragment.toastCenter(message: CharSequence) = activity?.toastCenter(message)

获取Drawable

fun FragmentActivity.getDrawable(@DrawableRes id: Int, width: Int = 0, height: Int = 0): Drawable? {
    val drawable = getDrawable(id) ?: return null
    var h = height
    var w = width
    if (w == 0) w = drawable.intrinsicWidth
    if (h == 0) h = w
    drawable.setBounds(0, 0, w, h)
    return drawable
}

Gson扩展

inline fun <reified T> Gson.fromJson(json: String): T {
    return fromJson<T>(json, T::class.java)
}

相关文章

网友评论

      本文标题:Activity、Fragment扩展方法Kotlin

      本文链接:https://www.haomeiwen.com/subject/ofvsactx.html