最近在学习Kotlin,所以这两天写了一个小Demo练练手(Api来自gank.io&zhuangbi.info);过程中碰到过不少以前遇到过的坑,因为之前没有记录下来的原因...长教训了。
懒加载目的是为了减少App浪费不必要的性能,只有在Fragment显示的时候并且没有加载过数据我们才去请求网络,刷新UI;
abstract class BaseFragment : Fragment() {
/**
* 视图是否加载完毕
*/
var isViewPrepare = false
/**
* 数据是否加载过了
*/
var hasLoadData = false
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view: View? = inflater?.inflate(getLayoutId(),container,false)
initViews(view)
return view
}
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
if (isVisibleToUser) {
lazyLoadDataIfPrepared()
}
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
isViewPrepare = true
lazyLoadDataIfPrepared()
}
private fun lazyLoadDataIfPrepared() {
if (userVisibleHint && isViewPrepare && !hasLoadData) {
lazyLoad()
hasLoadData = true
}
}
abstract fun lazyLoad()
abstract fun initViews(view: View?)
@LayoutRes
abstract fun getLayoutId():Int
}
我们将懒加载逻辑抽取到BaseFragment中,统一处理;
Demo已上传到github欢迎Star