简体   繁体   中英

Interface communication between two Fragments

I have implemented a master-detail view. With two fragments being displayed side by side on a large 10-inch screen. Fragment A Displays a list of orders. When an order is selected the details of that order are displayed in Fragment B . In fragments B after processing the order items. I want to notify Fragment A to update the UI and colour the processed order in the list of orders.

The current method that I have tried was creating an interface in Fragment B implementing the interface in Fragment A . However, this method does not seem to work as when I try and set the instance of the interface in the onAttach method the application crashes as the context is still the context of Fragment A .

@Override
public void onAttach(@NonNull Context context)
{
    super.onAttach(context);

    if (context instanceof OnStockAddedListener)
    {
        onStockAddedListener = (OnStockAddedListener) this.getActivity();

    } else
    {
        throw new ClassCastException(context.toString());
    }
}

How can i go about doing this.

Your fragments are hosted in an Activity , and that activity is what's passed to onAttach() . So your activity needs to be responsible for dispatching communication between your fragments.

So, in FragmentB, you cast your Activity to your listener interface when you're attached:

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    this.onStockAddedListener = (OnStockAddedListener) context;
}

And you implement the interface in your Activity:

public class MyActivity implements OnStockAddedListener {

    @Override
    public void onStockAdded(Stock stock) {
        FragmentA fragmentA = (FragmentA) getSupportFragmentManager()
                .findFragmentByTag(/* insert tag here */);

        fragmentA.handleStockAdded(stock);
    }
}

And you receive these messages in FragmentA:

public class FragmentA {

    public void handleStockAdded(Stock stock) {
        // update ui, or whatever else you need
    }
}

The main thing is to not think about FragmentA talking to FragmentB, or FragmentB talking to FragmentA. Instead, FragmentA and FragmentB both talk to the Activity, and the Activity can talk (as required) with either FragmentA or FragmentB. Everything flows through the activity.

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