Punnya Cipson
Punnya Cipson

Reputation: 63

How to prevent the calls to onCreate/onCreateView methods if the activity is finishing

I have an ActivityA and which host a fragmentA

onAttach() method of fragmentA, I need to check some conditions and if it fails, I need to finish the activity. I'm finishing the activity by calling getActivity().finish().

Even after I call the finish method, it is still calling the onCreate(), onCreateView() and onViewCreated() methods in fragmentA .

Is there any way I can stop these calls?

Upvotes: 3

Views: 1333

Answers (1)

Gennadii Saprykin
Gennadii Saprykin

Reputation: 4573

As @DeeV commented, I would check conditions before attaching a Fragment. In this case you don't have to deal with fragment lifecycle at all which is a cleaner way.

If this is not possible, there is a hacky way. You can call finish() in onAttach() and then use activity's method isFinishing() which returns a boolean flag. I think this should solve the problem.

E.g. in your fragment's onCreate method:

if (getActivity().isFinishing()) {
   // finish was called in onAttach
}

Upvotes: 1

Related Questions