Search code examples
androidandroid-fragmentssurfaceview

How should a fragment communicate with another class in Android?


I am currently building a camera app and have a problem: I have got a fragment that should contain a camerapreview. Now this camerapreview is a custom implementation as it extends SurfaceView.

Now my actual question is, how should my custom camerapreview talk to the fragment? For instance, I would like to be able to let my fragment know, that a touch event occured.

What approach should i use?


Solution

  • There are multiple ways to do this. If you don't need this to be reusable, then a solution with a higher amount of coupling is ok. In which case the fragment tells the view about itself and the view can just call a method:

    class CustomCameraPreview extends SurfaceView
    {
      FragmentA fragment;
      // Call from onCreateView() in the framgnet
      public void setFragment(FragmentA fragment)
      {
        this.fragment = fragment;
      }
    
      private void someMethod() {
        if ( fragment != null)
          fragment.callback();
    
      }
    
    }
    
    public class FragmentA extends Fragment {
    
      public void callback() {
        // called from the view
      }
    }
    

    If you need this to be more generic and reusable, then create a interface that contains the kind of callbacks the view would need to call and have the fragment implement that interface. This is basically the Observer pattern: http://en.wikipedia.org/wiki/Observer_pattern

    interface CameraPreviewListener {
    
       public void callback1() ;
       public void callback2() ;
    
    }
    
    class CameraPreview extends SurfaceView 
    {
      CameraPreviewListener listener;
      // Call from onCreateView() in the framgnet
      public void setFragment(CameraPreviewListener listener)
      {
        this.listener = listener;
      }
    
      private void someMethod1() {
        if ( listener != null)
          listener.callback1();    
      }
    
      private void someMethod2() {
        if ( listener != null)
          listener.callback2();    
      }
    
    }
    
    public class FragmentA extends Fragment implements CameraPreviewListener{
    
      public void callback1() {
        // called from the view
      }
    
      public void callback2() {
        // called from the view
      }
    }