简体   繁体   English

从FragB中的ListAdapter更新FragA中的SearchView?

[英]Updating SearchView in FragA from ListAdapter in FragB?

Scenario: You have two fragments, Fragment A which populates a ListAdapter, Fragment B which contains a SearchView with a ListAdapter. 场景:您有两个片段,片段A填充ListAdapter,片段B包含带有ListAdapter的SearchView。

Question: How does Fragment A update Fragment B's SearchView's ListAdapter? 问题:片段A如何更新片段B的SearchView的ListAdapter?

在此处输入图片说明

Fragments should not communicate directly. 片段不应直接通信。 You should use your activity for communication between child fragments. 您应该将活动用于子片段之间的通信。 You can create an interface which will define a contract for communication between fragments. 您可以创建一个接口,该接口将定义片段之间的通信协定。

public interface UpdateSerachViewList {
    void update(List<> data);
}

Activity will implement this interface. 活动将实现此接口。 Activity has access to both fragment1 and fragment 2. 活动可以访问fragment1和fragment 2。

If you want to send a message from frag1 to frag2 then fragment1 will in onAttach method save activity (Context param) as UpdateSerachViewList handler. 如果要将消息从frag1发送到frag2,则fragment1将在onAttach方法中将活动(上下文参数)保存为UpdateSerachViewList处理程序。

public class Frag1 extends Fragment {
    private UpdateSerachViewList mCallback;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        mCallback = (UpdateSerachViewList) context; 
// If exception is throws it measn you want to use frafgment with activity which does not implement communication contract. Design error
    }

    @Override
    public void onStart() {
        super.onStart();
        mCallback.update(...);
    }
}

In Activity you can then call what method you want on Fragment2. 然后,在“活动”中,您可以在Fragment2上调用所需的方法。 Or you can make frag2 also implement contract so you don't have to have direct reference to Frag2 but only to communication contract. 或者,您可以使frag2也实现合同,因此您不必直接引用Frag2,而只需直接引用通信合同即可。

You can access your Fragment by ID : 您可以通过ID访问您的Fragment

Fragment_1 fragment = (Fragment_1) getSupportFragmentManager().findFragmentById(R.layout.fr1);

fragment.updateSearchView();

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

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