简体   繁体   中英

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.

在此处输入图片说明

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.

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.

Activity ---> Fragment

Communication from Activity to Fragment is pretty straightforward. You really don't need a listener.

Let's say you have a method inside Fragment share()

public class MyFragment extends Fragment{

   public static MyFragment getInstance()
   {
       return new MyFragment();
   }

   ........

   public void share()
   {
        // do something
   }

}

How to call share() method from an Activity?

Get the reference of the Fragment and call the method. Simple!

MyFragment myFragment = MyFragment.getInstance();
myFragment.share();

You can see the full working code for Fragment to Fragment Communication

Just to add to Daniel Nugent's brilliant answer, here are snippets from my working code for delegating calls from Activity to Fragment.

I have a MVP architecture and I have defined the error handling method showError on the BaseView class and the code below demonstrates how to handle the UI on a TargetFragment class. I, specifically needed to hide my progress spinner on the fragment upon any error scenario. Here's the code snippets for the base classes:

public interface BaseView {
   void showError(ErrorResponse errorResponse);
}

public abstract class BaseActivity implements BaseView {
   @Override
   public void showError(ErrorResponse errorResponse) {
       // Check error condition or whatever
       // ...
       MaterialDialog dialog = new MaterialDialog.Builder(this)
                .title(R.string.dialog_error_title)
                .content(R.string.error_no_internet)
                .positiveText(R.string.dialog_action_ok)
                .build();
       dialog.show();
   }
}

public abstract class BaseFragment implements BaseView {
   @Override
   public void showError(ErrorResponse errorResponse) {
      ((BaseView) getActivity()).showError(errorResponse);
   }
}

And, this is how I handle UI inside my TargetFragment class:

public final class TargetFragment extends BaseFragment implements TargetView {
   @Override
   public void showError(ErrorResponse errorResponse) {
        super.showError(errorResponse);
        hideSpinner();
        
        // Do other UI stuff
        // ...
   }

   private void hideSpinner() {
       spinner.setVisibility(View.INVISIBLE);
   }
}

a clean solution:

public interface ShowFormula {
   public void showFormula(boolean show);
 }  

public class MyActivity implements ShowFormula {
   ...
   @Override
   public void showFormula(boolean show) {
     /** Your Code **/
   }
   ...
 }

public class MyFragment {
   private ShowFormula listener;
   ...
   @Override
   public void onAttach(Activity activity) {
     super.onAttach(activity);
     try {
       listener = (ShowFormula) activity;
       // listener.showFormula(show?);
     } catch (ClassCastException castException) {
       /** The activity does not implement the listener. **/
     }
   }
   ...
 }

simple thing make public method in fragments then call it on from your activity. eg

MyFragment fragment = new MyFragment(); fragment.doSomeThing();

doSomeThing() is a public method in MyFragment.

Activity to Fragment Communication via Interface:

public class MyActivity {

   private ShowFormula showFormulaListener;

   public interface ShowFormula {
      public void showFormula(boolean show);
  }

  public void setListener(MyFragment myFragment) {
      try {
      showFormulaListener = myFragment;
      } catch(ClassCastException e) {
     }
   }
 }

public class MyFragment implements ShowFormula{

     @Override
     public void onAttach(Activity activity) {
       super.onAttach(activity);
       try {
        ((MyActivity) activity).setListener(this);
        } catch (ClassCastException e) {
        Log.e(TAG, e.toString());
    }
}
     @Override
     public void showFormula(boolean show) {
     /** Your Code **/
     }
}

Once you are done setting this, you can call 'showFormulaListener.showFormula(boolVal)'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM