接上篇kotlin扩展函数一,本篇主要给出了自己在项目中用到的扩展函数和扩展属性,并没有穷举,相应的列举了一些.
Activity
activity中fragment相关操作
//----------添加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,像弹一个Toast,换算尺寸,获取屏幕尺寸等
//----------toast----------
fun Context.toast(text: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
Toast.makeText(this, text, duration).show()
}
//----------尺寸转换----------
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 一个View,设置Tablayout,设置View的上下左右边距
//---------- infalte 一个View----------
fun ViewGroup.inflate(layoutResId: Int): View = LayoutInflater.from(context).inflate(layoutResId, this, false)
//----------设置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))
}
}
//----------设置View的上边距 左右下同理 更改参数即可----------
var View.topMargin: Int
get():Int {
return (layoutParams as ViewGroup.MarginLayoutParams).topMargin
}
set(value) {
(layoutParams as ViewGroup.MarginLayoutParams).topMargin = value
}
Rxjava
对Rxjava做一些方法的扩展会让我们少写很多代码
//----------线程切换----------
fun <T> Observable<T>.schedulerHelper(): Observable<T> =
this.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
//----------统一返回处理结果----------
fun <T> handleResult(): FlowableTransformer<BaseResultBean<T>, T> =
FlowableTransformer { response ->
response.flatMap {
if (it.code == 200) {
TODO Something
} else {
Flowable.error(Throwable())
}
}
}
TextView
传进来一个颜色id,TextView直接设置颜色爽不爽?直接设置上下左右的drawable爽么
//----------设置TextView的文字颜色---------
fun TextView.setColor(resId: Int) {
this.setTextColor(ContextCompat.getColor(context, resId))
}
//----------设置textview 的左drawable 同理其他三个---------
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
有时候需要设置一段文字不用颜色是不是要写很多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
}
当然还有很多其他的扩展方法,在是用的过程中,如果一个方法会频繁用到,不妨扩展一下减少代码量,用起来的还是挺不错的.