在子片段onCreateView之后调用父片段的onCreateView

时间:2019-12-10 06:42:09

标签: android fragment parent-child fragment-oncreateview

我有一个ParentFragment和一个从其延伸的ChildFragment。我在两个片段的onCreateView方法中都放置了一个日志。但是ParentFragment的{​​{1}}被称为最后一个。

但是,活动之间相同的父子关系正在产生预期的结果。首先调用父级活动onCreateView,然后调用子级活动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中的binding

ChildFragment

当前,由于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之后被调用,因此我理解崩溃。

0 个答案:

没有答案