调用Fragment构造函数导致异常。导航架构组件

Mos*_*afa 7 android android-fragments android-architecture-components

我正在使用导航体系结构组件库,我的应用程序的起点是以下片段:

class MainFragment : BaseFragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_main, container, false)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }
}
Run Code Online (Sandbox Code Playgroud)

继承于抽象类BaseFragment

abstract class BaseFragment : Fragment() {

}
Run Code Online (Sandbox Code Playgroud)

当我运行我的应用程序时,我得到:

 Unable to instantiate fragment io.example.MainFragment: calling Fragment constructor caused an exception
Run Code Online (Sandbox Code Playgroud)

但是,如果使用MainFragmentExtended Fragment而不是则不会发生这种情况BaseFragment。是什么原因?这与导航体系结构组件的工作方式有关吗?

Nux*_*Nux 17

我有类似的问题,因为我在MyBaseFragment 中有 val

protected abstract val gpsMsg: String
Run Code Online (Sandbox Code Playgroud)

在片段附加到上下文之前,我在其他片段中以这种方式覆盖。

override val gpsMsg: String = getString(R.string.gps_not_enabled)
Run Code Online (Sandbox Code Playgroud)

所以潜在的错误是因为 context 为 null 并且 getString 使用getResources()which returns requireContext().getResources()。并且在requireContext()源代码中会抛出错误。

public final Context requireContext() {
    Context context = getContext();
    if (context == null) {
        throw new IllegalStateException("Fragment " + this + " not attached to a context.");
    }
    return context;
}
Run Code Online (Sandbox Code Playgroud)

所以抛出的错误导致片段没有被实例化。所以我建议在覆盖时小心上下文。

  • 谢谢,这很有帮助。添加lazy { getString(R.string.label_aab) }后它就得到了修复。 (2认同)