Can we call onClick event of a button inside a fragment layout in MainActivity, instead of in that class of fragment?

Viewed 48

I have created an onClick event of a button inside a fragment layout, and write it in main activity class. It works !. However, I tried create same onCLick event of the button in the fragment layout in the fragment class. It also works !

My question is what difference if we write an event and call it in main activity (button is inside of fragment layout) VS write it and call it in fragment class where the button belong to. Both are same ? Any pros and cons ?

1 Answers

The main difference is where you call the 'onClick()'.

If you are calling the onclick after replacing the fragment, then it will work as expected.

But, If you are calling it before initializing fragment, then the app will crash. So never ever do that.

Related