有很多app啟動頁還是老一套的splashactivity,然后跳轉到mainactivity,首先splash加載了一遍資料,然后進入到main之后也會加載資料,所以導致兩次加載都要等待,如果反過來呢
這里可以先加載mainactivity,然后在去觸發splashactivity,當然,這樣也有缺陷,有的main中可能加載資料量大,會導致進入splash之前卡頓,所以一般是在同一個布局中,把splashactivity變成splashfragment
這樣布局中默認的就是splash頁了,然后main中的資料也在同時得到了加載,等splash結束后一般main已經初始化完全了,所以不用在次加載,可以直接顯示出來,這一步就節省了大量的等待時間,比其它花里胡哨的優化實用有效多了

實作也比較簡單,在你原來的MainActivity布局中添加一層布局
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools"> <data> <variable name="model" type="com.strong.ui.MainViewModel" /> </data> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.viewpager2.widget.ViewPager2 android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="@dimen/dp_0" app:layout_constraintBottom_toTopOf="@+id/lin_bottom" app:layout_constraintTop_toTopOf="parent" /> <com.strong.ui.view.menu.BottomMenuView android:id="@+id/lin_bottom" android:layout_width="@dimen/dp_0" android:layout_height="wrap_content" android:background="@color/white" android:clipChildren="false" android:clipToPadding="false" android:orientation="horizontal" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout> <FrameLayout android:id="@+id/fl_splash" android:layout_width="match_parent" android:layout_height="match_parent" tools:visibility="gone" /> </FrameLayout> </layout>View Code
然后把splashfragment動態添加到容器中

這樣啟動頁就默認顯示執行了
然后模擬加載資料完成后關閉啟動頁,splashfragment移除后直接顯示mainactivity布局
class SplashFragment : BaseBindFragment<FragmentSplashBinding, SplashViewModel>() { override fun layoutId() = R.layout.fragment_splash override fun providerVMClass() = SplashViewModel::class.java override fun initData(bundle: Bundle?) { binding.model = mViewModel //模擬加載圖片 var count = 0f val mHandler = Handler(Looper.getMainLooper()) val mRunnable = object :Runnable { override fun run() { count+=20 binding.pbTime.setProgress(count) if (count >= binding.pbTime.getMax()) { mHandler.removeCallbacks(this) activity!!.window.setBackgroundDrawableResource(R.color.white) //移除啟動頁 activity!!.supportFragmentManager.beginTransaction().remove(this@SplashFragment).commitAllowingStateLoss() }else{ mHandler.postDelayed(this,500) } } } mHandler.postDelayed(mRunnable,500) } }View Code
如果mainactivity中加載量過大在優化自己的啟動加載流程,這樣是不是加載不卡頓也省了加載時間
github:https://github.com/1024477951/KotlinStrong
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/263711.html
標籤:其他
上一篇:kotlin 圓形進度條
