如何在Kotlin进行装载
我的MainActivity包含一个加载4个片段的ViewPager,每个片段都应该从服务器加载大量数据 因此,当我的应用程序想要第一次运行时,几乎需要3秒以上的时间,其他时间例如,如果你退出应用程序,但没有从“最近应用程序”窗口清除它并重新打开它,几乎需要1秒钟 加载时,它会显示一个白色屏幕 在数据准备就绪之前,有没有办法不显示白色屏幕,而是显示自己的图像?如何在Kotlin进行装载,kotlin,loading,splash-screen,Kotlin,Loading,Splash Screen,我的MainActivity包含一个加载4个片段的ViewPager,每个片段都应该从服务器加载大量数据 因此,当我的应用程序想要第一次运行时,几乎需要3秒以上的时间,其他时间例如,如果你退出应用程序,但没有从“最近应用程序”窗口清除它并重新打开它,几乎需要1秒钟 加载时,它会显示一个白色屏幕 在数据准备就绪之前,有没有办法不显示白色屏幕,而是显示自己的图像? 类似于启动页的内容?如果在主线程上执行长时间运行的操作,则可能会遇到错误 每个片段的布局都应该有一个最初可见的加载视图和数据视图。大概是
类似于启动页的内容?如果在主线程上执行长时间运行的操作,则可能会遇到错误 每个片段的布局都应该有一个最初可见的加载视图和数据视图。大概是这样的: 非代码 框架布局 加载\u视图可以显示进度微调器或其他内容,大小与父级匹配 content\u视图可能是一个RecyclerView,初始可见性=消失,大小与父级匹配 /框架布局 您需要在后台线程或协同程序上执行长时间运行的操作,然后在数据准备好在UI中显示时交换这两个视图的可见性 您不应该直接处理片段代码中的数据加载,因为片段是一个UI控制器。Android Jetpack库为此提供了ViewModel类。您可以像这样设置ViewModel。在本例中,MyData可以是任何内容。在你的情况下,它可能是一个列表或一组东西
class MyBigDataViewModel(application: Application): AndroidViewModel(application) {
private val _myBigLiveData = MutableLiveData<MyData>()
val myBigLiveData: LiveData<MyData>() = _myBigLiveData
init {
loadMyBigData()
}
private fun loadMyBigData() {
viewModelScope.launch { // start a coroutine in the main UI thread
val myData: MyData = withContext(Dispatchers.Default) {
// code in this block is done on background coroutine
// Calculate MyData here and return it from lambda
// If you have a big for-loop, you might want to call yield()
// inside the loop to allow this job to be cancelled early if
// the Activity is closed before loading was finished.
//...
return@withContext calculatedData
}
// LiveData can only be accessed from the main UI thread so
// we do it outside the withContext block
_myBigLiveData.value = myData
}
}
}
您的布局在加载时应具有备用视图。列表视图应该是隐藏的。然后在数据准备好显示时交换可见性。您需要在后台异步任务中加载数据,这样您就不会冒得到ANR的风险。这可以通过在ViewModel中为数据使用协程来实现。这里要解释的太多了,但是你可以找到很多教程。谢谢你的回复,不幸的是,我对android不太熟悉,我正在提高我的技能。你能给我推荐一个教程吗?这里有各种各样的主题。我将从ViewModel上的官方android文档开始。当我有时间的时候,我会在下面发布一个快速概述。非常感谢。@Tenfour04
class MyFragment: Fragment() {
// ViewModels should not be instantiated directly, or they won't be scoped to the
// UI life cycle correctly. The activityViewModels delegate handles instantiation for us.
private val model: MyBigDataViewModel by activityViewModels()
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
model.myBigLiveData.observe(this, Observer<MyData> { myData ->
loading_view.visibility = View.GONE
content_view.visibility = View.VISIBLE
// use myData to update the view content
})
}
}