Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
490 views
in Technique[技术] by (71.8m points)

java - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...