Communication between components

When building large complex apps, you find yourself wanting to communicate between components of your app. For example, when you inflate a Fragment with a custom view, you may want your Fragment to communicate with the View and/or vice versa. More than once, I have come across code like this in Android projects to solve this problem:
// Custom View class
public class MyView extends View {
    public void setAndDoSomething(Fragment fragment, String text) {
        if (text.contains("NO") {
            fragment.doSomething();
        }
    }
}

// Fragment class
public class MyFragment extends Fragment {
    View myView;
    public void onSomeAction() {
        myView.setAndDoSomething(this, "NO");
    }
    public void doSomething() {
        //some logic
    }
}

As you can see, the whole Fragment object is passed to the view only for it to call a method doSomething() which lies in the MyFragment class. There are a few things that are not right here; what if we want to use the setAndDoSomething() method in MyView with some other Fragment, say MyOtherFragment? You can understand it quickly gets ugly.

Well, Interfaces are designed for this type of communication. You can have your Fragment or Fragments implement an Interface which does this for you. Instead of sending your whole Fragment object, send a part of it!

// Custom View class
public class MyView extends View {
    public void setAndDoSomething(MyInterface interface, String text) {
        if (text.contains("NO") {
            interface.doSomething();
        }
    }
    
    interface MyInterface {
        void doSomething();
    }
}

// Fragment class
public class MyFragment extends Fragment implements MyView.MyInterface {
    View myView;
    public void onSomeAction() {
        myView.setAndDoSomething(this, "NO");
    }
    
    @Override
    public void doSomething() {
        //some logic
    }
}

As you can see, the Interface is the contract between your View and any Fragments implementing it to doSomething() when you setAndDoSomething(). This way you’re not worried about leaking the Fragment (in case if your View implements static methods and holds on to the Fragment?) and the interface takes care of sending the right calls to the Fragment. Easy and simple :)

Comments

Popular posts from this blog

MY Pursuit

Value of Education and Education of Values

Random Android Learnings