kotlin擴(kuò)展函數(shù)(二)

接上篇kotlin擴(kuò)展函數(shù)一,本篇主要給出了自己在項(xiàng)目中用到的擴(kuò)展函數(shù)和擴(kuò)展屬性,并沒有窮舉,相應(yīng)的列舉了一些.

Activity

activity中fragment相關(guān)操作

 //----------添加fragment----------
fun AppCompatActivity.addFragment(layoutRes: Int, otherFragment: Fragment) {
    val fm = supportFragmentManager
    fm.beginTransaction()
            .add(layoutRes, otherFragment)
            .commit()
}

 //----------隱藏fragment----------
fun AppCompatActivity.hideShowFragment(hideFragment: Fragment, showFragment: Fragment) {
    supportFragmentManager.transact {
        hide(hideFragment).show(showFragment)
    }
}

private inline fun FragmentManager.transact(action: FragmentTransaction.() -> Unit) {
    beginTransaction().apply {
        action()
    }.commitAllowingStateLoss()
}

Context

有很多方法需要用到context,像彈一個(gè)Toast,換算尺寸,獲取屏幕尺寸等

//----------toast----------
fun Context.toast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(this, text, duration).show()
}

//----------尺寸轉(zhuǎn)換----------
fun Context.dp2px(dpValue: Float): Int {
    val scale = resources.displayMetrics.density
    return (dpValue * scale + 0.5f).toInt()
}

//----------屏幕尺寸----------
fun Context.getScreenWidth(): Int {
    var wm: WindowManager = this.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            ?: return resources.displayMetrics.widthPixels
    var point = Point()
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        wm.defaultDisplay.getRealSize(point)
    } else {
        wm.defaultDisplay.getSize(point)
    }
    return point.x
}

fun Context.getScreenHeight(): Int {
    var wm: WindowManager = this.getSystemService(Context.WINDOW_SERVICE) as WindowManager
            ?: return resources.displayMetrics.heightPixels
    var point = Point()
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
        wm.defaultDisplay.getRealSize(point)
    } else {
        wm.defaultDisplay.getSize(point)
    }
    return point.y
}

View

infalte 一個(gè)View,設(shè)置Tablayout,設(shè)置View的上下左右邊距

//---------- infalte 一個(gè)View----------
fun ViewGroup.inflate(layoutResId: Int): View = LayoutInflater.from(context).inflate(layoutResId, this, false)

//----------設(shè)置tablayout自定義view的tab----------
fun TabLayout.setTab(titles: Array<String>) {
    titles.forEach {
        val view = inflate(R.layout.layout_tab_title)
        val tvTitle = view.findViewById<TextView>(R.id.tv_tab_name)
        tvTitle.text = it
        addTab(newTab().setCustomView(view))
    }
}

//----------設(shè)置View的上邊距 左右下同理 更改參數(shù)即可----------
var View.topMargin: Int
    get():Int {
        return (layoutParams as ViewGroup.MarginLayoutParams).topMargin
    }
    set(value) {
        (layoutParams as ViewGroup.MarginLayoutParams).topMargin = value
    }

Rxjava

對(duì)Rxjava做一些方法的擴(kuò)展會(huì)讓我們少寫很多代碼

//----------線程切換----------
fun <T> Observable<T>.schedulerHelper(): Observable<T> =
        this.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())

//----------統(tǒng)一返回處理結(jié)果----------
fun <T> handleResult(): FlowableTransformer<BaseResultBean<T>, T> =
        FlowableTransformer { response ->
            response.flatMap {
                if (it.code == 200) {
                    TODO Something
                } else {
                    Flowable.error(Throwable())
                }
            }
        }

TextView

傳進(jìn)來一個(gè)顏色id,TextView直接設(shè)置顏色爽不爽?直接設(shè)置上下左右的drawable爽么

//----------設(shè)置TextView的文字顏色---------
fun TextView.setColor(resId: Int) {
    this.setTextColor(ContextCompat.getColor(context, resId))
}

//----------設(shè)置textview 的左drawable 同理其他三個(gè)---------
fun TextView.setDrawableLeft(resId: Int) {
    var drawable = this.context.resources.getDrawable(resId)
    drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
    this.setCompoundDrawables(drawable, null, null, null)
}

String

有時(shí)候需要設(shè)置一段文字不用顏色是不是要寫很多span?

//----------拼接不同顏色的字符串---------
fun CharSequence.formatStringColor(color: Int, start: Int, end: Int): SpannableString {
    return this.setSpan(ForegroundColorSpan(ContextCompat.getColor(Utils.getContext(), color)), start, end)
}

private fun CharSequence.setSpan(span: ParcelableSpan, start: Int, end: Int): SpannableString {
    val spannableString = SpannableString(this)
    spannableString.setSpan(span, start, end, Spanned.SPAN_INCLUSIVE_INCLUSIVE)
    return spannableString
}

當(dāng)然還有很多其他的擴(kuò)展方法,在是用的過程中,如果一個(gè)方法會(huì)頻繁用到,不妨擴(kuò)展一下減少代碼量,用起來的還是挺不錯(cuò)的.

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容