Alex Alex - 18 days ago 6
Android Question

Updating Parent Fragment from Child Fragment

In my android application, I have two Fragments. Parent Fragment contains list of available Filter Types and when a particular Filter Type is clicked (in Parent Fragment - Yellow Background) corresponding Child Fragment (Pink Background) opens with list of available options for selected filter type. My requirement is once User select/deselect an option in child fragment, it should reflect/update option count (Green color) in parent Fragment.

Please check attached wireframe.

enter image description here

Answer

You can use Otto Bus for comunications between Fragments, fragments-activities, services, etc.

Maybe, the first time you can be a little weird if you have not used before but it is very powerful and very easy to use. You can find the library and a tutorial here:

http://square.github.io/otto/

An example. In your adapter or where you have your item click event you cand send a Object by the Bus.

In your bus you invoque the post method and pass the object. (I recommended create a singleton for Bus).

The singleton Bus Provider.

/**
 * Canal de comunicacion
 */
public class BusProvider {

    private static final Bus REST_BUS = new Bus(ThreadEnforcer.ANY);
    private static final Bus UI_BUS = new Bus();

    private BusProvider() {};

    public static Bus getRestBusInstance() {
        return REST_BUS;
    }

    public static Bus getUIBusInstance () {
        return UI_BUS;
    }
}

You send a Object in the bus (in your child fragment) like this:

BusProvider.getUIBusInstance().post(itemSelected);

And in your parent fragment you subscribe for this event:

@Subscribe
public void activitySelected(final Item itemSelected) {

}

Hope it helps you!!