调用 Fragment 构造函数导致异常,kotlin?

WIS*_*SHY 7 navigation android fragment kotlin

我正在使用导航控制器导航到另一个片段

导航到第二个片段

private fun moveToNextScreen(userId: String) {
    val bundle = bundleOf("userId" to userId)
    binding.googleLogin.findNavController().navigate(
        R.id.action_loginFragment_to_signupFragment, bundle
    )
}
Run Code Online (Sandbox Code Playgroud)

我要导航到的片段

class UserSetupFragment : Fragment() {
private lateinit var binding: FragmentUserSetupBinding

var optionCb = mutableListOf<AppCompatCheckBox>()
var optionsList =
    ArrayList<String>(Arrays.asList(*resources.getStringArray(R.array.profile_options)))

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    binding = FragmentUserSetupBinding.inflate(inflater, container, false)
    return binding.getRoot()
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    createOptionsCheckBox()
}

private fun createOptionsCheckBox() {
    for (option in optionsList) {
        val checkBox = AppCompatCheckBox(activity)
        checkBox.setText(option)
        checkBox.setTextColor(ContextCompat.getColor(requireActivity(), android.R.color.black));
        optionCb.add(checkBox)
        binding.optionsLayout.addView(checkBox)
    }
}

}
Run Code Online (Sandbox Code Playgroud)

我得到了例外

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=66957, result=-1, data=Intent { (has extras) }} to activity {com.patient.reach52/com.patient.reach52.view.authenticate.AuthenticateActivity}: androidx.fragment.app.Fragment$InstantiationException: Unable to instantiate fragment com.patient.reach52.view.authenticate.UserSetupFragment: calling Fragment constructor caused an exception
Run Code Online (Sandbox Code Playgroud)

这里有什么问题?

And*_*ana 9

resources在将片段附加到活动之前,您无法访问。所以你必须延迟实例化optionsList

class UserSetupFragment : Fragment() {
    lateinit var optionsList: List<String>

    override fun onAttach(context: Context) {
        super.onAttach(context)
        optionsList = resources.getStringArray(R.array.profile_options).toList()
    }
...
Run Code Online (Sandbox Code Playgroud)


Kir*_*uck 1

之前的评论关于原因是正确的 - 您试图过早访问资源
,但我没有看到正确的解决方案
,避免
在当前情况下使用 Lateinit尝试

val optionsList by lazy {
        resources.getStringArray(R.array.profile_options).toList()
    }
Run Code Online (Sandbox Code Playgroud)