Best practice to reference the parent activity of a fragment?

前端 未结 3 1684
借酒劲吻你
借酒劲吻你 2020-12-16 16:04

I\'ve been working a lot with fragments lately and I was just curious as to what the best practice is for using a reference to a fragment\'s parent activity. Would it be bet

3条回答
  •  爱一瞬间的悲伤
    2020-12-16 16:40

    If you are in the fragment which is called from some activity, to get the reference to parent activity you can call it inside onViewCreated() or later hook methods of fragment directly by, it is just to make sure that parent activity is not null

    getActivity()
    

    If you want to really make sure you need to check first

    if (getActivity() != null){ // then your logic with getActivity()}
    

提交回复
热议问题