Kotlin中Firebase登录成功后Activity向Fragment传值失效问题
Activity向Fragment传值失效问题修复
核心错误点
- 传值逻辑所在页面错误:你在
RegisterActivity中执行Fragment事务创建FourthFragment后,立刻调用startActivity跳转到MainActivity,此时Register页面会被系统压入返回栈甚至直接销毁,你在Register的FragmentManager中添加的Fragment根本不会显示在MainActivity中,属于无效操作。 - Fragment生命周期时序错误:在
FourthFragment的onCreateView方法中,你在inflate布局返回前就调用requireView()查找控件,此时Fragment的视图树还未创建完成,会直接触发空指针,该段逻辑完全无法执行。 - Fragment实例不匹配:你在
Register中创建的FourthFragment实例,和MainActivity实际加载展示的FourthFragment是完全独立的两个对象,前者携带的参数无法自动同步给后者。
修复方案
1. 修改Register页面跳转逻辑
删除原有无效的passUserData()方法,直接将需要传递的字符串放入启动MainActivity的Intent中,修改showMainMenu()方法如下:
private fun showMainMenu(){ val goMainMenu = Intent(this, MainActivity::class.java) // 传入需要展示的字符串 goMainMenu.putExtra("sayhi", "Hello") startActivity(goMainMenu) // 销毁注册页,避免用户按返回键回到认证页面 finish() }
同时删掉setup()方法里两处认证成功回调中对passUserData()的调用,只保留showMainMenu()即可。
2. 在MainActivity中给Fragment设置参数
找到MainActivity中加载FourthFragment的代码位置,在创建Fragment实例时,把从Intent中取到的参数封装到Bundle中设置给Fragment,示例代码如下:
// 创建Fragment实例 val fourthFragment = FourthFragment() val args = Bundle() // 从Intent中取出Register传入的字符串 args.putString("sayhi", intent.getStringExtra("sayhi") ?: "") fourthFragment.arguments = args // 执行Fragment事务将Fragment添加到页面容器中 supportFragmentManager.beginTransaction() .replace(R.id.你自己布局里的Fragment容器ID, fourthFragment) .commit()
如果你是通过Navigation组件、ViewPager2等组件管理Fragment,只需要在对应创建FourthFragment实例的位置,按上述方式给arguments赋值即可。
3. 修正FourthFragment的生命周期逻辑
删掉onCreateView中操作控件的错误代码,只保留布局加载逻辑,控件赋值操作统一放在onViewCreated中执行,修正后代码如下:
import android.os.Bundle import androidx.fragment.app.Fragment import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView enum class ProviderType{ BASIC } class FourthFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { // 仅加载布局,不做任何控件操作 return inflater.inflate(R.layout.fragment_fourth, container, false) } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // 视图创建完成后再读取参数、给TextView赋值 arguments?.let { val sayHello = it.getString("sayhi", "") val showtext : TextView = view.findViewById(R.id.emailShow) showtext.text = sayHello } } }
注意:Fragment的arguments参数需要在Fragment被提交添加到FragmentManager之前设置,否则会出现参数丢失的问题。
内容的提问来源于stack exchange,提问作者Sergio26
相关产品推荐
相关产品推荐

