有很多app启动页还是老一套的splashactivity,然后跳转到mainactivity,首先splash加载了一遍数据,然后进入到main之后也会加载数据,所以导致两次加载都要等待,如果反过来呢
这里可以先加载mainactivity,然后在去触发splashactivity,当然,这样也有缺陷,有的main中可能加载数据量大,会导致进入splash之前卡顿,所以一般是在同一个布局中,把splashactivity变成splashfragment
这样布局中默认的就是splash页了,然后main中的数据也在同时得到了加载,等splash结束后一般main已经初始化完全了,所以不用在次加载,可以直接显示出来,这一步就节省了大量的等待时间,比其它花里胡哨的优化实用有效多了
实现也比较简单,在你原来的MainActivity布局中添加一层布局
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<?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>
然后把splashfragment动态添加到容器中
这样启动页就默认显示执行了
然后模拟加载数据完成后关闭启动页,splashfragment移除后直接显示mainactivity布局
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
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) } }
如果mainactivity中加载量过大在优化自己的启动加载流程,这样是不是加载不卡顿也省了加载时间