Kotlin中无需点击实现Fragment间X秒后自动跳转(如闪屏转登录场景)
核心疑问解答
- 能否用Intent实现Fragment跳转?
不行。Intent是Android用于四大组件(Activity、Service、BroadcastReceiver、ContentProvider)之间通信的组件,Fragment是依附于Activity存在的UI片段,不能通过Intent直接跳转。你当前的代码逻辑是直接启动新的AuthActivity,属于跨Activity切换,不符合你要在同一个Activity内实现两个Fragment切换的需求。
具体实现步骤
步骤1:修改导航配置文件nav_auth.xml,添加跳转Action和动画配置
你需要先在两个Fragment之间声明导航路由,同时配置跳转过渡动画,跳转后自动将闪屏页从回退栈移除,避免用户按返回键回到闪屏页:
<?xml version="1.0" encoding="utf-8"?> <navigation 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" android:id="@+id/nav_auth" app:startDestination="@id/splashScreen"> <fragment android:id="@+id/splashScreen" android:label="fragment_splash_screen" tools:layout="@layout/fragment_splash_screen"> <!-- 跳转到登录页的Action --> <action android:id="@+id/action_splash_to_login" app:destination="@id/loginFragment" app:popUpTo="@id/splashScreen" app:popUpToInclusive="true" <!-- 跳转动画配置,可替换为你自定义的动画文件 --> app:enterAnim="@anim/slide_in_right" app:exitAnim="@anim/slide_out_left" app:popEnterAnim="@anim/slide_in_left" app:popExitAnim="@anim/slide_out_right" /> </fragment> <fragment android:id="@+id/loginFragment" android:label="fragment_login" tools:layout="@layout/fragment_login" /> </navigation>
步骤2:将闪屏逻辑迁移到SplashScreenFragment中
闪屏的动画、延迟跳转逻辑属于闪屏Fragment的业务逻辑,需要放到SplashScreenFragment的onViewCreated生命周期方法中执行,不要写在Activity里:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // 加载闪屏页自身的展示动画 val topAnim = AnimationUtils.loadAnimation(requireContext(), R.anim.top_animation) val bottomAnim = AnimationUtils.loadAnimation(requireContext(), R.anim.bottom_animation) val image = view.findViewById<ImageView>(R.id.imageView) val slogan = view.findViewById<TextView>(R.id.textView) image.startAnimation(topAnim) slogan.startAnimation(bottomAnim) // 延迟3秒跳转逻辑 val mainHandler = Handler(Looper.getMainLooper()) val jumpRunnable = Runnable { // 用导航控制器执行跳转,自动应用配置的过渡动画 findNavController().navigate(R.id.action_splash_to_login) } mainHandler.postDelayed(jumpRunnable, 3000) // 页面销毁时移除延迟任务,避免内存泄漏和崩溃 viewLifecycleOwner.lifecycle.addObserver(object : DefaultLifecycleObserver { override fun onDestroy(owner: LifecycleOwner) { super.onDestroy(owner) mainHandler.removeCallbacks(jumpRunnable) } }) }
补充确认项
确保承载两个Fragment的Activity布局中已经正确配置了NavHostFragment,关联了你写的nav_auth导航图:
<androidx.fragment.app.FragmentContainerView android:id="@+id/nav_host_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:navGraph="@navigation/nav_auth" app:defaultNavHost="true" />
不需要再创建单独的AuthActivity,你之前写的启动Activity的逻辑可以直接删除。
内容的提问来源于stack exchange,提问作者labyrinth
相关产品推荐
相关产品推荐

