前言
Kotlin 中有很多内置的扩展函数,非常好用,可以代替很多需要封装的Java工具类,本文主在列举一些发现的好用扩展函数;
本文也会不断维护,大佬们有新的扩展函数,或者自己写的感觉好用扩展函数也可以加进来;
日志打印
internal const val DEBUG = true
internal const val TAG = "shuxin.wei"
fun Any?.logI(tag: String = TAG, debug: Boolean = true) {
if (DEBUG && debug) {
Log.i(tag, this.toString())
}
}
fun Any?.logD(tag: String = TAG, debug: Boolean = true) {
if (DEBUG && debug) {
Log.d(tag, this.toString())
}
}
fun Any?.logE(tag: String = TAG, debug: Boolean = true) {
if (DEBUG && debug) {
Log.e(tag, this.toString())
}
}
fun Any?.logW(tag: String = TAG, debug: Boolean = true) {
if (DEBUG && debug) {
Log.w(tag, this.toString())
}
}
fun Any?.logP(tag: String = TAG, debug: Boolean = true) {
if (DEBUG && debug) {
println("$tag : $this")
}
}
fun printThread(tag: String = TAG) {
"$tag: ThreadName:${Thread.currentThread().name} ThreadId: ${Thread.currentThread().id}".logD(tag)
}
异步
- 简介
可以在Activity、Fragment、Context上下文中方便线程切换,以及处理了可能发生的内存泄漏;
Boolean返回值表示是否执行了传入的函数;
将这段代码粘贴到AS中就可以看见入参和上下文;
文件地址:https://github.com/Kotlin/anko
class CoroutinesActivity : AppCompatActivity() {
val doAsync: Future<Unit> = "test".doAsync {
val get: String? = this.weakRef.get()
printThread(get ?: "test")
"test"
}
val doAsyncResult: Future<String> = "test".doAsyncResult {
val get: String? = this.weakRef.get()
printThread(get ?: "")
return@doAsyncResult "test"
}
val activityUiThread: Boolean = AnkoAsyncContext(WeakReference(this@CoroutinesActivity)).activityUiThread {
}
baseContext.runOnUiThread {
}
val uiThread: Boolean = AnkoAsyncContext(WeakReference("test")).uiThread {
}
val activityUiThreadWithContext: Boolean = AnkoAsyncContext(WeakReference(this@CoroutinesActivity)).activityUiThreadWithContext {
}
val ankoContext = AnkoContext.create(this@CoroutinesActivity, this@CoroutinesActivity)
val activityUiThread1: Boolean = AnkoAsyncContext(WeakReference(ankoContext)).activityUiThread {
}
val activityUiThreadWithContext1: Boolean = AnkoAsyncContext(WeakReference(ankoContext)).activityUiThreadWithContext {
}
Fragment().runOnUiThread {
}
val supportFragmentUiThread:Boolean = AnkoAsyncContext(WeakReference(Fragment())).supportFragmentUiThread {
}
}