简体   繁体   English

如何从活动中的片段管理onclicklistener?

[英]how to manage onclicklistener from fragments in the activity?

I have a question I hope someone can solve it. 我有一个问题,希望有人能解决。

I have 4 fragments for 1 activity, but just 2 of them are displayed, so I have buttons to navigate between these fragments. 我有1个活动的4个片段,但只显示其中2个,因此我有在这些片段之间导航的按钮。

All clicks must be executed in the activity, so this knows which fragment ahs to replace, so all "OnClickListener" must to implement the "OnclickListener" of the activity. 所有单击都必须在活动中执行,因此它知道要替换的片段ahs,因此所有“ OnClickListener”都必须实现活动的“ OnclickListener”。

How can I solve this? 我该如何解决? Thank you! 谢谢!

There is a standard solution for this: 有一个标准的解决方案:

Define an interface, say ClickCallbacks: 定义一个接口,例如ClickCallbacks:

interface ClickCallbacks {
    void onClick(stuff... );
}

In each fragment, implement onAttach, like this: 在每个片段中,实现onAttach,如下所示:

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try { clickListener = (ClickCallbacks) activity; }
    catch (ClassCastException e) {
        throw new ClassCastException(
            activity.toString() + " must implement ClickCallbacks");
    }
}

Finally, implement the interface in your Activity. 最后,在您的Activity中实现该接口。

This is described in pretty clear detail in the Fragment documentation here: Fragments 此处的“片段”文档中对此进行了非常详细的描述: 片段

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

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