简体   繁体   English

两个片段之间的接口通信

[英]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. 在10英寸大屏幕上并排显示两个片段。 Fragment A Displays a list of orders. 片段A显示订单列表。 When an order is selected the details of that order are displayed in Fragment B . 选择订单后,该订单的详细信息将显示在片段B中 In fragments B after processing the order items. 在片段B中处理了订单项之后。 I want to notify Fragment A to update the UI and colour the processed order in the list of orders. 我想通知片段A更新UI,并在订单列表中为已处理的订单上色。

The current method that I have tried was creating an interface in Fragment B implementing the interface in Fragment A . 我已经尝试过的当前方法是创造在片段B实现在片段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 . 但是,此方法似乎不起作用,因为当我尝试在onAttach方法中设置接口的实例时,应用程序崩溃了,因为上下文仍然是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() . 您的片段托管在一个Activity ,该活动就是传递给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: 因此,在FragmentB中,连接后将Activity投射到侦听器接口:

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

And you implement the interface in your Activity: 然后在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: 并且您在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. 最主要的是不要考虑FragmentA与FragmentB对话,或FragmentB与FragmentA对话。 Instead, FragmentA and FragmentB both talk to the Activity, and the Activity can talk (as required) with either FragmentA or FragmentB. 相反,FragmentA和FragmentB都与Activity对话,并且Activity可以(根据需要)与FragmentA或FragmentB对话。 Everything flows through the activity. 一切都流经活动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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