Han
Han

Reputation: 650

How do I call functions in fragment from another?

I put two fragments in an activity. What I want to do is to hide a view from say fragment A when I click a button in fragment B. I have the hiding function in fragment A but how do I call it in fragment B? I tried:

((FragmentA)getActivity().getFragmentManager().findFragmentById(R.id.fragment_a)).hideLivePreview();

but it gives me a null pointer exception...please help

Upvotes: 2

Views: 2838

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006819

You do not want to do this in general. Fragment A and Fragment B should not directly communicate, since Fragment A and Fragment B may not both be on the screen at the same time all of the time. They might be side-by-side on a large screen but displayed via separate activities on smaller screens. IMHO, activities should mediate all communications between fragments. If you have two fragments that are too tightly coupled for that, they should not be separate fragments in the first place.

All that being said, you are getting a NullPointerException because there is no fragment with that ID in the activity.

Upvotes: 4

Related Questions