获取颜色
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)
}
网友评论