Kotlin4Android学习总结三:拓展函数再举例

上一篇已经提到了Kotlin的拓展函数,拓展函数算是目前发现的Kotlin的一个非常闪光的点,使用起来有时候有种暗爽,Kotlin的拓展函数是来干嘛的?准确的说就是来革工具类的命的。这一篇继续举例拓展函数。

1,EditText的拓展函数

还记得Java代码中EditText的监听文字变化的监听器,写法如下:

edit_search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                input=s.toString().trim();
                if (!TextUtils.isEmpty(input)){
                    //do something
                    searchData();
                }else {
                    //do something
                }
            }
        });

使用kotlin我们就可以写一个拓展函数来简化上面的代码,拓展函数如下:

fun EditText.setTextChangeListener(body: (key: String) -> Unit) {
    addTextChangedListener(object : TextWatcher {
        override fun afterTextChanged(s: Editable?) {
        }

        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            body(s.toString())
        }
    })
}

如何使用

edit_search.setTextChangeListener {
            if (!TextUtils.isEmpty(it)){
                //do something
                searchData();
            }else{
                //do something
            }
        }

代码是不是简洁了许多,我写Kotlin的时候有时候简洁的总感觉少了点什么[笑哭],其实并没有少干,只是在拓展函数里面已经做了

2,获取各种尺寸

还记得一般情况下我们的项目中都会自己写很多工具类,例如写一个DisplayUtils,用于获取屏幕尺寸啊,或者dp,sp与px的转换等等。

/**
 * 获取屏幕尺寸
 */
fun Activity.getDisplaySize(): Point {
    val point = Point()
    val display = windowManager.defaultDisplay
    display.getSize(point)
    return point
}

/**
 * dp转换为px
 *
 * @param dp
 * @return
 */
fun Context.dpToPx(dp: Float): Float {
    val px = getAbsValue(dp, TypedValue.COMPLEX_UNIT_DIP)
    return px
}

fun Context.getAbsValue(value: Float, unit: Int): Float {
    return applyDimension(unit, value, resources.displayMetrics)
}

使用

mysrcollview.setTitleBarHeight(dpToPx(100f))

3,获取资源

/**
* 获取颜色资源
* Extension method to Get Color for resource for Context.
*/
fun Context.getColor(@ColorRes id: Int) = ContextCompat.getColor(this, id)

/**
* 获取Drawable资源
* Extension method to Get Drawable for resource for Context.
*/
fun Context.getDrawable(@DrawableRes id: Int) = ContextCompat.getDrawable(this, id)

在写这篇博客的时候我发现已经有人写了关于拓展函数的库,里面的例子更多,推荐去看看,收藏以下

博客地址
库地址

你可能感兴趣的:(Kotlin4Android学习总结三:拓展函数再举例)