Kotlin的拓展功能

说实话这个我是最近才知道的 虽然学习kotlin还没有多长时间 但是我已经深深的被他吸引了
进入正题

DateExt

/**
 *  2018-4-6 11:11:11转为毫秒
 *  @param format 时间的格式,默认是按照yyyy-MM-dd HH:mm:ss来转换
 */
fun String.toMills(format: String = "yyyy-MM-dd HH:mm:ss") =
    SimpleDateFormat(format, Locale.getDefault()).parse(this).time

/**
 * Long类型时间戳转为字符串的日期格式
 * @param format 时间的格式,默认是按照yyyy-MM-dd HH:mm:ss来转换
 */
fun Long.toDate(format: String = "yyyy-MM-dd HH:mm:ss") =
    SimpleDateFormat(format, Locale.getDefault()).format(Date(this))

/**
 * 到秒
 */
fun Long.toDateSec() = toDate()

/**
 * 到分
 */
fun Long.toDateMin() = toDate("yyyy-MM-dd HH:mm")

/**
 * 到日
 */
fun Long.toDateDay() = toDate("yyyy-MM-dd")

FragmentExt


/**
 * 在Activity中进行Fragment的增加 显示 隐藏 显示隐藏 替换 移除
 */
fun FragmentActivity.add(layoutId: Int, fragment: Fragment) {
    supportFragmentManager.beginTransaction()
        .add(layoutId, fragment)
        .commitAllowingStateLoss()
}

fun FragmentActivity.show(fragment: Fragment) {
    supportFragmentManager.beginTransaction()
        .show(fragment)
        .commitAllowingStateLoss()
}

fun FragmentActivity.hide(fragment: Fragment) {
    supportFragmentManager.beginTransaction()
        .hide(fragment)
        .commitAllowingStateLoss()
}


fun FragmentActivity.showHide(showFragment: Fragment, hideFragment: Fragment) {
    supportFragmentManager.beginTransaction()
        .show(showFragment)
        .hide(hideFragment)
        .commitAllowingStateLoss()
}


fun FragmentActivity.replace(layoutId: Int, f: Fragment) {
    supportFragmentManager.beginTransaction()
        .replace(layoutId, f)
        .commitAllowingStateLoss()
}

fun FragmentActivity.remove(f: Fragment) {
    supportFragmentManager.beginTransaction()
        .remove(f)
        .commitAllowingStateLoss()
}


/**
 * 在Fragment中进行Fragment的增加 显示 隐藏 显示隐藏 替换 移除
 */
fun Fragment.add(layoutId: Int, fragment: Fragment) {
    childFragmentManager.beginTransaction()
        .add(layoutId, fragment)
        .commitAllowingStateLoss()
}

fun Fragment.hide(fragment: Fragment) {
    childFragmentManager.beginTransaction()
        .hide(fragment)
        .commitAllowingStateLoss()
}

fun Fragment.show(fragment: Fragment) {
    childFragmentManager.beginTransaction()
        .show(fragment)
        .commitAllowingStateLoss()
}

fun Fragment.showHide(showFragment: Fragment, hideFragment: Fragment) {
    childFragmentManager.beginTransaction()
        .show(showFragment)
        .hide(hideFragment)
        .commitAllowingStateLoss()
}

fun Fragment.replace(layoutId: Int, f: Fragment) {
    childFragmentManager.beginTransaction()
        .replace(layoutId, f)
        .commitAllowingStateLoss()
}

fun Fragment.remove(f: Fragment) {
    childFragmentManager.beginTransaction()
        .remove(f)
        .commitAllowingStateLoss()
}

GsonExt

/**
 * 实体类转化为json
 */
fun Any.parse2Json() = Gson().toJson(this)

/**
 * json转化为Bean
 */
inline fun  String.parse2Bean() = Gson().fromJson(this, object : TypeToken() {}.type)

/**
 * json转为List
 */
inline fun  String.parse2Array(Clazz: Class>) = Gson().fromJson(this, Clazz).asList()

ResourceExt

 */
fun Context.color(id: Int) = ContextCompat.getColor(this, id)

fun Context.string(id: Int): String = resources.getString(id)

fun Context.stringArray(id: Int): Array = resources.getStringArray(id)

fun Context.drawable(id: Int) = ContextCompat.getDrawable(this, id)

fun Context.dimen(id: Int) = resources.getDimension(id)

fun Context.dp2px(dp: Float): Int = (dp * resources.displayMetrics.density + 0.5f).toInt()

fun Context.px2dp(px: Float): Int = (px / resources.displayMetrics.density + 0.5f).toInt()

fun Context.sp2px(sp: Float): Int = (sp * resources.displayMetrics.scaledDensity + 0.5f).toInt()

fun Context.px2sp(px: Float): Int = (px / resources.displayMetrics.scaledDensity + 0.5f).toInt()


/**
 * 从Fragment中获取资源
 */
fun Fragment.color(id: Int) = context!!.color(id)

fun Fragment.string(id: Int) = context!!.string(id)

fun Fragment.stringArray(id: Int) = context!!.stringArray(id)

fun Fragment.drawable(id: Int) = context!!.drawable(id)

fun Fragment.dimen(id: Int) = context!!.dimen(id)

fun Fragment.dp2px(dp: Float): Int = context!!.dp2px(dp)

fun Fragment.px2dp(px: Float): Int = context!!.px2dp(px)

fun Fragment.sp2px(sp: Float): Int = context!!.sp2px(sp)

fun Fragment.px2sp(px: Float): Int = context!!.px2sp(px)


/**
 * 从Dialog中获取资源
 */
fun Dialog.color(id: Int) = context.color(id)

fun Dialog.string(id: Int) = context.string(id)

fun Dialog.stringArray(id: Int) = context.stringArray(id)

fun Dialog.drawable(id: Int) = context.drawable(id)

fun Dialog.dimen(id: Int) = context.dimen(id)

fun Dialog.dp2px(dp: Float): Int = context.dp2px(dp)

fun Dialog.px2dp(px: Float): Int = context.px2dp(px)

fun Dialog.sp2px(sp: Float): Int = context.sp2px(sp)

fun Dialog.px2sp(px: Float): Int = context.px2sp(px)

/**
 * 从service中获取资源
 */
fun Service.color(id: Int) = applicationContext.color(id)

fun Service.string(id: Int) = applicationContext.string(id)

fun Service.stringArray(id: Int) = applicationContext.stringArray(id)

fun Service.drawable(id: Int) = applicationContext.drawable(id)

fun Service.dimen(id: Int) = applicationContext.dimen(id)

fun Service.dp2px(dp: Float): Int = applicationContext.dp2px(dp)

fun Service.px2dp(px: Float): Int = applicationContext.px2dp(px)

fun Service.sp2px(sp: Float): Int = applicationContext.sp2px(sp)

fun Service.px2sp(px: Float): Int = applicationContext.px2sp(px)

/**
 * 从View中获取资源
 */
fun View.color(id: Int) = context.color(id)

fun View.string(id: Int) = context.string(id)

fun View.stringArray(id: Int) = context.stringArray(id)

fun View.drawable(id: Int) = context.drawable(id)

fun View.dimen(id: Int) = context.dimen(id)

fun View.dp2px(dp: Float): Int = context.dp2px(dp)

fun View.px2dp(px: Float): Int = context.px2dp(px)

fun View.sp2px(sp: Float): Int = context.sp2px(sp)

fun View.px2sp(px: Float): Int = context.px2sp(px)

/**
 * 从RecyclerView中获取资源
 */
fun RecyclerView.ViewHolder.color(id: Int) = itemView.color(id)

fun RecyclerView.ViewHolder.string(id: Int) = itemView.string(id)

fun RecyclerView.ViewHolder.stringArray(id: Int) = itemView.stringArray(id)

fun RecyclerView.ViewHolder.drawable(id: Int) = itemView.drawable(id)

fun RecyclerView.ViewHolder.dimenPx(id: Int) = itemView.dimen(id)

fun RecyclerView.ViewHolder.dp2px(dp: Float): Int = itemView.dp2px(dp)

fun RecyclerView.ViewHolder.px2dp(px: Float): Int = itemView.px2dp(px)

fun RecyclerView.ViewHolder.sp2px(sp: Float): Int = itemView.sp2px(sp)

fun RecyclerView.ViewHolder.px2sp(px: Float): Int = itemView.px2sp(px)


SharedPreferencesExt

fun Any.SP(name: String = BuildConfig.APPLICATION_ID) =
    BaseApplication.app.getSharedPreferences(name, Context.MODE_PRIVATE)

/**
 * 批处理
 */
fun SharedPreferences.edit(action: SharedPreferences.Editor.() -> Unit) {
    edit().apply { action() }.apply()
}

/**
 * 传入基本类型
 */
fun SharedPreferences.put(key: String, value: Any) {
    edit {
        when (value) {
            is String -> putString(key, value)
            is Int -> putInt(key, value)
            is Boolean -> putBoolean(key, value)
            is Float -> putFloat(key, value)
            is Long -> putLong(key, value)
        }
    }
}

fun SharedPreferences.clear() {
    edit { clear() }
}

StringExt

/**
 * 是否是手机号
 * 1+后面10位
 */
fun String.isPhone() = "1\\d{10}$".toRegex().matches(this)

/**
 * 是否是邮箱地址
 */
fun String.isEmail() = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?".toRegex().matches(this)

/**
 * 是否是身份证号码
 */
fun String.isIDCard() = "[1-9]\\d{16}[a-zA-Z0-9]".toRegex().matches(this)

/**
 * 是否是中文字符
 */
fun String.isChinese() = "^[\u4E00-\u9FA5]+$".toRegex().matches(this)

/**
 * 获取当前字符串的md5
 */
fun String.md5() = EncryptUtils.encryptMD5ToString(this)

/**
 * 判断字符串是否为空或者是null的任意变化
 * 曾经出现过后台返回"Null" 然后判断isNullOrEmpty()通过 显示在界面上的时候悲剧了
 */
fun String?.isNull() = this == null || isNullOrEmpty() || toLowerCase().trim() == "null"

ViewExt

/**
 * 设置View的高度
 * @param height 设置的高度
 */
fun View.height(height: Int): View {
    val params = layoutParams
    params.height = height
    layoutParams = params
    return this
}

/**
 * 设置View高度,限制在min和max之内
 * @param min 最小高度
 * @param max 最大高度
 */
fun View.limitHeight(min: Int, max: Int): View {
    val params = layoutParams
    val h = params.height
    when {
        h < min -> params.height = min
        h > max -> params.height = max
        else -> params.height = h
    }
    layoutParams = params
    return this
}

/**
 * 设置View的宽度
 * @param width 设置的宽度
 */
fun View.width(width: Int): View {
    val params = layoutParams
    params.width = width
    layoutParams = params
    return this
}

/**
 * 设置View宽度,限制在min和max之内
 * @param w
 * @param min 最小宽度
 * @param max 最大宽度
 */
fun View.limitWidth(min: Int, max: Int): View {
    val params = layoutParams
    val w = params.width
    when {
        w < min -> params.width = min
        w > max -> params.width = max
        else -> params.width = w
    }
    layoutParams = params
    return this
}

/**
 * 设置View的宽度和高度
 * @param width 要设置的宽度
 * @param height 要设置的高度
 */
fun View.widthAndHeight(width: Int, height: Int): View {
    val params = layoutParams
    params.width = width
    params.height = height
    layoutParams = params
    return this
}

/**
 * 设置View的margin  默认保留原设置
 * @param leftMargin    距离左的距离
 * @param topMargin     距离上的距离
 * @param rightMargin   距离右的距离
 * @param bottomMargin  距离下的距离
 */
fun View.margin(
    leftMargin: Int = Int.MAX_VALUE,
    topMargin: Int = Int.MAX_VALUE,
    rightMargin: Int = Int.MAX_VALUE,
    bottomMargin: Int = Int.MAX_VALUE
): View {
    val params = layoutParams as ViewGroup.MarginLayoutParams
    if (leftMargin != Int.MAX_VALUE)
        params.leftMargin = leftMargin
    if (topMargin != Int.MAX_VALUE)
        params.topMargin = topMargin
    if (rightMargin != Int.MAX_VALUE)
        params.rightMargin = rightMargin
    if (bottomMargin != Int.MAX_VALUE)
        params.bottomMargin = bottomMargin
    layoutParams = params
    return this
}

/**
 * 设置控件Visible
 */
fun View.visible() {
    visibility = View.VISIBLE
}

/**
 * 设置控件Gone
 */
fun View.gone() {
    visibility = View.GONE
}

/**
 * 设置控件Invisible
 */
fun View.invisible() {
    visibility = View.INVISIBLE
}

/**
 * 设置是否可见
 * @param visibleOrGone true - Visible false - Gone
 */
fun View.setVisible(visibleOrGone: Boolean) {
    visibility = if (visibleOrGone) View.VISIBLE else View.GONE
}

/**
 * 判断控件是否为Gone
 */
val View.isGone: Boolean
    get() {
        return visibility == View.GONE
    }

/**
 * 判断控件是否为Visible
 */
val View.isVisible: Boolean
    get() {
        return visibility == View.VISIBLE
    }

/**
 * 判断控件是否为InVisible
 */
val View.isInvisible: Boolean
    get() {
        return visibility == View.INVISIBLE
    }

/**
 * 获取View的Bitmap
 * 支持RecyclerView ScrollView 基础控件 不支持ListView了
 * 注意:使用这个方法的时候必须要在View测量完毕之后才能进行
 */
fun View.toBitmap(): Bitmap {
    if (measuredWidth == 0 || measuredHeight == 0) {
        throw RuntimeException("警告⚠️警告⚠️这个时候View还没有测量完毕")
    }
    return when (this) {
        is RecyclerView -> {
            this.scrollToPosition(0)
            this.measure(
                View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)
            )

            val screenshot = Bitmap.createBitmap(width, measuredHeight, Bitmap.Config.ARGB_8888)
            val canvas = Canvas(screenshot)

            if (background != null) {
                background.setBounds(0, 0, width, measuredHeight)
                background.draw(canvas)
            } else {
                canvas.drawColor(Color.WHITE)
            }
            this.draw(canvas)

            this.measure(
                View.MeasureSpec.makeMeasureSpec(width, View.MeasureSpec.EXACTLY),
                View.MeasureSpec.makeMeasureSpec(height, View.MeasureSpec.AT_MOST)
            )
            screenshot
        }
        is ScrollView -> {
            var totalHeight = 0
            for (i in 0 until this.childCount) {
                totalHeight += this.getChildAt(i).height
                this.getChildAt(i).setBackgroundColor(Color.parseColor("#ffffff"))
            }
            val screenshot = Bitmap.createBitmap(this.getWidth(), totalHeight, Bitmap.Config.RGB_565)
            val canvas = Canvas(screenshot)
            this.draw(canvas)
            screenshot
        }
        else -> {
            val screenshot = Bitmap.createBitmap(measuredWidth, measuredHeight, Bitmap.Config.ARGB_4444)
            val canvas = Canvas(screenshot)
            if (background != null) {
                background.setBounds(0, 0, width, measuredHeight)
                background.draw(canvas)
            } else {
                canvas.drawColor(Color.WHITE)
            }
            draw(canvas)
            screenshot
        }
    }
}


//是否点击的标签 点击后为true 600毫秒后设置为false
var isViewClicked = false
// 延时操作
var mViewClickRunnable = Runnable { isViewClicked = false }

/**
 * 设置控件的点击时间
 * @param method 点击事件
 */
fun View.onClick(method: () -> Unit) {
    if (!hasOnClickListeners()) {
        setOnClickListener {
            if (!isViewClicked) {
                isViewClicked = true
                method()
            }
            removeCallbacks(mViewClickRunnable)
            postDelayed(mViewClickRunnable, 600)
        }
    }
}

你可能感兴趣的:(Kotlin的拓展功能)