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

Posted

技术标签:

【中文标题】调用 Fragment 构造函数导致异常,kotlin?【英文标题】:calling Fragment constructor caused an exception, kotlin? 【发布时间】:2020-09-22 09:26:06 【问题描述】:

我正在使用navigationcontroller 导航到另一个片段

导航到第二个片段

private fun moveToNextScreen(userId: String) 
    val bundle = bundleOf("userId" to userId)
    binding.googleLogin.findNavController().navigate(
        R.id.action_loginFragment_to_signupFragment, bundle
    )

我正在导航到的片段

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)
    



我遇到了异常

java.lang.RuntimeException: Failure delivering result ResultInfowho=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

这里怎么了?

【问题讨论】:

【参考方案1】:

在片段附加到活动之前,您无法访问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()
    
...

【讨论】:

【参考方案2】:

您无法从 FragmentClass 访问资源。您应该在 onCreateView 或 onCreate 中定义任何您想要的内容。

例子:

class ExampleFragment : Fragment()

     private lateinit var example : String


    override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View 
    _binding = FragmentExampleBinding.inflate(inflater, container, false)
    val view = binding.root

    example = resources.getString(R.string.random)
    
    return view

【讨论】:

以上是关于调用 Fragment 构造函数导致异常,kotlin?的主要内容,如果未能解决你的问题,请参考以下文章

由于 Fragment 类中没有公共构造函数方法,在 android 中旋转设备后出现异常

为啥在构造函数中抛出异常会导致空引用?

fragment.onCreateView 导致空指针异常

构造函数的 void 修饰符导致异常

开发中关于Fragment异常的两个问题

java.lang.IllegalStateException:Fragment XXXFragment{409864b0} not attached to Activity