上一篇已經(jīng)提到了Kotlin的拓展函數(shù),拓展函數(shù)算是目前發(fā)現(xiàn)的Kotlin的一個(gè)非常閃光的點(diǎn),使用起來(lái)有時(shí)候有種暗爽,Kotlin的拓展函數(shù)是來(lái)干嘛的?準(zhǔn)確的說(shuō)就是來(lái)革工具類的命的。這一篇繼續(xù)舉例拓展函數(shù)。
1,EditText的拓展函數(shù)
還記得Java代碼中EditText的監(jiān)聽(tīng)文字變化的監(jiān)聽(tīng)器,寫法如下:
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我們就可以寫一個(gè)拓展函數(shù)來(lái)簡(jiǎn)化上面的代碼,拓展函數(shù)如下:
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
}
}
代碼是不是簡(jiǎn)潔了許多,我寫Kotlin的時(shí)候有時(shí)候簡(jiǎn)潔的總感覺(jué)少了點(diǎn)什么[笑哭],其實(shí)并沒(méi)有少干,只是在拓展函數(shù)里面已經(jīng)做了
2,獲取各種尺寸
還記得一般情況下我們的項(xiàng)目中都會(huì)自己寫很多工具類,例如寫一個(gè)DisplayUtils,用于獲取屏幕尺寸啊,或者dp,sp與px的轉(zhuǎn)換等等。
/**
* 獲取屏幕尺寸
*/
fun Activity.getDisplaySize(): Point {
val point = Point()
val display = windowManager.defaultDisplay
display.getSize(point)
return point
}
/**
* dp轉(zhuǎn)換為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)
在寫這篇博客的時(shí)候我發(fā)現(xiàn)已經(jīng)有人寫了關(guān)于拓展函數(shù)的庫(kù),里面的例子更多,推薦去看看,收藏以下