MutableContextWrapper
MutableContextWrapper是Context家族中一员。其显著特点是可以动态替换baseContext来达到预加载需要Context创建的资源。
预加载工具类
不多解释了,里面运用了IdelHandler和MutableContextWrapper,在资源不紧张时返回预加载View。
object PreViewHelper {
private val viewMap = ConcurrentHashMap<Class<*>, View>()
fun <T> preCreateView(clazz: Class<T>) {
if (Thread.currentThread().id != Looper.getMainLooper().thread.id) {
throw Exception("must call preCreateView in main thread")
}
Looper.myQueue().addIdleHandler(MessageQueue.IdleHandler {
try {
viewMap[clazz] =
//反射实现,如果没有反射工具,百度即可
ReflectUtils.reflect(clazz)
.newInstance(MutableContextWrapper(AppUtils.getApp()))
.get()
} catch (e: Exception) {
}
return@IdleHandler false
})
}
fun <T> getView(activity: Activity, clazz: Class<T>): T? {
val view = viewMap[clazz]
if (view != null) {
(view.context as MutableContextWrapper).baseContext = activity
viewMap.remove(clazz)
return view as? T
}
return null
}
}