I use a fragment only inside one specific parent activity. Now I wonder if there are any drawbacks if I call methods in the parent activity directly from the included fragment like this:
getActivity().someMethodInParentActivitiy()
A more common solution would be to define a formal listener interface in the fragment to call back to the parent activity and then make the activity implement that interface.
Are there any reasons (e.g. reliability or speed) why I should use the second more complex solution instead of direct method calls from the fragment to the activity?
If you want to start a new instance of mFragmentFavorite , you can do so via an Intent . Intent intent = new Intent(this, mFragmentFavorite. class); startActivity(intent); If you want to start aFavorite instead of mFragmentFavorite then you only need to change out their names in the created Intent .
Additional cast need to be done:
Activity activity123 = getActivity(); if(activity123 instanceof ParentActivity) { ((ParentActivity) activity123).someMethodInParentActivity(); }
however as @pawelzieba wrote if u want to use that fragment in another activities which is probably the case it will not work this way.. Cheers
Don't look at the performance at the begining. Remember "premature optimization is the root of all evil". The second approach is better because your fragment could be used in different activities. The first approach introduces more dependencies in your code, the fragment is dependent to the activity type. You're loosing ability to test, reuse, small complex. It may seem to be simpler right now, but in the future you'll see ;-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With