Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Activity methods from Fragment

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?

like image 563
Anguel Avatar asked Feb 09 '12 14:02

Anguel


People also ask

Can you start an activity from a fragment?

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 .


2 Answers

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

like image 184
Ewoks Avatar answered Oct 06 '22 03:10

Ewoks


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 ;-)

like image 41
pawelzieba Avatar answered Oct 06 '22 03:10

pawelzieba