概述
某些業務場景下,為了提高用戶體驗,我們可能需要在前一個頁面就將下一個頁面的資料準備好,減少用戶后續操作的時間,因為Activity在設計上采用了低耦合,高度的隔離使得傳統的預加載Activity方案不夠優雅,現提供一種更加優雅的預加載方案,可以預先加載好布局和頁面資料,
github:https://github.com/long8313002/PreloadingActivity
效果展示

使用
說明:因為庫使用的是kotlin開發,需要在專案配置kotlin開發環境
庫參考
implementation 'com.zhangzheng.preloading.activity:library:1.0.0'
使用示例
val intent = Intent(this,TestActivity::class.java)
intent.putExtra("id",1111)
PreLoading.preLoading(this,intent,TestPreLoadingView::class.java)
textView.setOnClickListener {
startActivity(intent)
}
默認情況下,當打開預加載頁面后,頁面銷毀后,預加載的實體也會一起被銷毀,當下次再進行就需要重新加載布局和資料,如果需要保留預加載的資料,多次重復使用,可以設定引數 autoDestroy = false ,如下:
PreLoading.preLoading(this,intent,TestPreLoadingView::class.java,false)
預加載頁面實作
考慮到不同的專案使用的基類Activity會有所不同,為了通用性,未直接定制Activity,而是提供 AbsPreLoadingView 來通過組合的方式來實作,為了使用方便,這邊提供了一個繼承于Activity的基類,實際使用中可以參考這個類來實作自己的基類,如下:
示范基類
abstract class AbsPreLoadingActivity : Activity() {
abstract fun preLoadingViewClass() : KClass<out AbsPreLoadingView>
private lateinit var preLoadingView: AbsPreLoadingView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
preLoadingView =preLoadingViewClass().getOrCreate(intent, this)
setContentView(preLoadingView)
preLoadingView.callCreate(savedInstanceState)
}
override fun onStart() {
super.onStart()
preLoadingView.callStart()
}
override fun onResume() {
super.onResume()
preLoadingView.callResume()
}
override fun onPause() {
super.onPause()
preLoadingView.callPause()
}
override fun onStop() {
super.onStop()
preLoadingView.callStop()
}
override fun onDestroy() {
super.onDestroy()
preLoadingView.callDestroy()
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
preLoadingView.onActivityResult(requestCode, resultCode, data)
}
}
使用示范
class TestActivity : AbsPreLoadingActivity() {
override fun preLoadingViewClass() = TestPreLoadingView::class
}
class TestPreLoadingView(context: Context) : AbsPreLoadingView(context) {
override fun resId() = R.layout.activity_test_list
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
requestTestData(intent?.getIntExtra("id",0)?:0)
}
override fun onResume() {
super.onResume()
}
private fun requestTestData(id:Int){
Thread {
Thread.sleep(1000)
val listData = ArrayList<String>()
listData.add("$id === > 1")
listData.add("$id === > 2")
listData.add("$id === > 3")
listData.add("$id === > 4")
listData.add("$id === > 5")
listData.add("$id === > 6")
listData.add("$id === > 7")
listData.add("$id === > 8")
listData.add("$id === > 9")
listData.add("$id === > 10")
listData.add("$id === > 11")
listData.add("$id === > 12")
Handler(Looper.getMainLooper()).post {
listview.adapter = ArrayAdapter(context,android.R.layout.simple_list_item_1,listData)
}
}.start()
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/172417.html
標籤:其他
上一篇:iOS Presenting view controllers on detached view controllers is discouraged
