Kotlin实战指南十一:扩展函数

转载请标明出处:https://blog.csdn.net/zhaoyanjun6/article/details/94640013
本文出自【赵彦军的博客】


扩展函数是Kotlin提供的非常酷的特性,在编写Android应用程序时,你将发现自己会大量使用它。

我们必须承认Android框架有时做些事有点困难,在Java中我们唯一的解决方案是把我们要做事封装起来,或利用可读性差的类静态方法。

你想怎样才能加额外函数到框架类?这就是Kotlin扩展函数允许我们做的。

在Android中我们要显示和隐藏一个 view ,通常这样做:

class MainActivity : AppCompatActivity() {

    private var tv: TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        tv = findViewById(R.id.tv)
        tv?.visibility = View.VISIBLE  //view显示
        tv?.visibility = View.GONE   //view隐藏

    }
}

那么用扩展函数怎么做,我们首先对 View扩展两个方法

//扩展函数,view隐藏
fun View.gone() {
        visibility = View.GONE
}

//扩展函数,view显示
fun View.visible() {
        visibility = View.VISIBLE
}

使用:

class MainActivity : AppCompatActivity() {

    private var tv: TextView? = null

    //扩展函数,view隐藏
    fun View.gone() {
        visibility = View.GONE
    }

    //扩展函数,view显示
    fun View.visible() {
        visibility = View.VISIBLE
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        tv = findViewById(R.id.tv)
        tv?.visible()  //view显示
        tv?.gone()   //view隐藏

    }
}

一些常用的扩展函数

我们对一些可能会用到的扩展函数做了一个整理:

ViewExtends.kt 对 View 的扩展

import android.view.View

fun View.gone() {
    visibility = View.GONE
}

fun View.visible() {
    visibility = View.VISIBLE
}

var View.topMargin: Int
    get():Int {
        return (layoutParams as ViewGroup.MarginLayoutParams).topMargin
    }
    set(value) {
        (layoutParams as ViewGroup.MarginLayoutParams).topMargin = value
    }

var View.bottomMargin: Int
    get():Int {
        return (layoutParams as ViewGroup.MarginLayoutParams).bottomMargin
    }
    set(value) {
        (layoutParams as ViewGroup.MarginLayoutParams).bottomMargin = value
    }

var View.rightMargin: Int
    get():Int {
        return (layoutParams as ViewGroup.MarginLayoutParams).rightMargin
    }
    set(value) {
        (layoutParams as ViewGroup.MarginLayoutParams).rightMargin = value
    }

var View.leftMargin: Int
    get():Int {
        return (layoutParams as ViewGroup.MarginLayoutParams).leftMargin
    }
    set(value) {
        (layoutParams as ViewGroup.MarginLayoutParams).leftMargin = value
    }

TextViewExtends.kt 对 TextView 的扩展

import android.widget.TextView

/**
 * 设置颜色直接使用colors.xml中定义的颜色即可
 */
fun TextView.setColor(resId: Int) {
    this.setTextColor(resources.getColor(resId))
}

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)
}

fun TextView.setDrawableRight(resId: Int) {
    var drawable = this.context.resources.getDrawable(resId)
    drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
    this.setCompoundDrawables(null, null, drawable, null)
}

fun TextView.setDrawableTop(resId: Int) {
    var drawable = this.context.resources.getDrawable(resId)
    drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
    this.setCompoundDrawables(null, drawable, null, null)
}

fun TextView.setDrawableBottom(resId: Int) {
    var drawable = this.context.resources.getDrawable(resId)
    drawable.setBounds(0, 0, drawable.minimumWidth, drawable.minimumHeight)
    this.setCompoundDrawables(null, null, null, drawable)
}

ContextExtends.kt 对Context的扩展

import android.content.Context
import android.view.Gravity
import android.widget.Toast

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

fun Context.toast(resId: Int, duration: Int = Toast.LENGTH_SHORT) {
    Toast.makeText(this, resId, duration).show()
}

fun Context.centerToast(resId: Int, duration: Int = Toast.LENGTH_SHORT) {
    var t = Toast.makeText(this, resId, duration)
    t.setGravity(Gravity.CENTER, 0, 0)
    t.show()
}

//----------尺寸转换----------

fun Context.dp2px(dpValue: Float): Int {
    val scale = resources.displayMetrics.density
    return (dpValue * scale + 0.5f).toInt()
}

fun Context.px2dp(pxValue: Float): Int {
    val scale = resources.displayMetrics.density
    return (pxValue / scale + 0.5f).toInt()
}

fun Context.sp2px(spValue: Float): Int {
    val scale = resources.displayMetrics.scaledDensity
    return (spValue * scale + 0.5f).toInt()
}

fun Context.px2sp(pxValue: Float): Int {
    val scale = resources.displayMetrics.scaledDensity
    return (pxValue / scale + 0.5f).toInt()
}

总结

我在github 上找了一个常用的扩展库,大家可以看看,非常有用。https://github.com/shiweibsw/Android-kotlin-extend-utils


个人微信号:zhaoyanjun125 , 欢迎关注

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章