Communicate from Activity to Fragment using Interface



I have searched SO for this problem but was not able to find anything which would solve my problem. My problem is, I have a activity which contains FrameLayout which is constantly updated with different fragments. The top view and bottom view are going to remain same hence they are in the layout of the activity.

As you can see bottom view has a button on click of that i want to make changes in the fragments which will be present in the FrameLayout.

enter image description here

I have created a interface

public interface ShowFormula {

    void showFormula(boolean show);

}

which i will use to implement in the fragment. Now the main problem in my MainActivity class i am trying to initialize the interface but not able to as i am getting class cast exception

showFormula = (ShowFormula) this;//yes i know this is wrong

How should i initialize this in order to communicate with the fragment. Main goal is to toggle the view in fragments on click of the button in activity.

Thanks in advance.

Answer

You don’t need to use an interface to make calls from an Activity to a Fragment. Just keep a reference to the current Fragment, and call into a public method in the Fragment from the Activity.

If you have multiple Fragments and you don’t want to keep a reference for each one, you can create a Fragment base class, declare the common method in the base class, and then implement that method override in all of your Fragments that inherit from the base Fragment. Then, keep one reference of the base Fragment type, and always have it set to the Fragment that is shown currently.



Source: stackoverflow