0

我有一个ParentFragment和一个ChildFragment从它延伸出来的。我放置了onCreateView两个片段的登录方法。但是ParentFragment'sonCreateView被最后调用。

但是,活动之间相同的父子关系正在产生预期的结果。首先调用父活动onCreate,然后调用子活动onCreate

ParentFragment

abstract class ParentFragment<T: ViewDataBinding>: Fragment(){

    @LayoutRes
    abstract fun getLayoutResId(): Int

    protected lateinit var binding: T


    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        Log.d("-----------", "onCreateView ParentFragment")
        return DataBindingUtil.inflate<T>(inflater, getLayoutResId(), container, false).apply { binding = this }.root
    }

ChildFragment

class ChildFragment: ParentFragment<FragmentChildBinding>() {

    @LayoutRes
    override fun getLayoutResId() = R.layout.fragment_child

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.d("-----------", "onCreateView ChildFragment")

        return inflater.inflate(R.layout.fragment_child, container, false)
    }

片段结果:

2019-12-10 10:54:28.054 32450-32450/blabla.yeahyeah D/-----------: onCreateView ChildFragment
2019-12-10 10:54:28.054 32450-32450/blabla.yeahyeah D/-----------: onCreateView ParentFragment

活动结果:

2019-12-10 10:54:27.796 32450-32450/blabla.yeahyeah D/-----------: onCreate ParentActivity
2019-12-10 10:54:27.931 32450-32450/blabla.yeahyeah D/-----------: onCreate ChildActivity

你能帮忙吗?我错过了什么还是预期的行为?

我覆盖的原因onCreateView是我试图像这样将我的连接viewModel到我bindingChildFragment

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.d("-----------", "onCreateView ChildFragment")

        val viewModel = getViewModel()
        binding.viewModel = viewModel //CRASH HAPPENING HERE. THIS VARIABLE IS NOT INITIALIZED
        binding.lifecycleOwner = this

        return binding.root
    }

目前,我正在崩溃,因为binding当我从ChildFragment. 由于该变量需要在其中初始化ParentFragmentParentFragment在之后被调用ChildFragment,因此据我所知,我正在崩溃。

4

0 回答 0