多个片段的一个接口

多个片段的一个接口

本文介绍了多个片段的一个接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我我是否正确解决了该问题,还是应该改走另一条路线?

Can someone please tell me if I'm solving this correctly or if I should go another route?

这是一个简化的示例:我有1个活动和2个片段.每个片段都有一个按钮,单击该按钮后,会将单击中继到活动,然后在活动中弹出一个Toast.

This is a simplified example: I have 1 Activity and 2 Fragments. Each Fragment has a button that when clicked, relays the click back to the Activity and a Toast pops up within the Activity.

我知道一个Fragment通过接口与Activity通信.但是,如果我有多个具有相似接口的片段,该怎么办?例如,这里的两个片段都使用onClick类型的界面来与活动进行通信

I know that a Fragment communicates with an Activity through an interface. But what If I have multiple Fragments that have a similar Interface. For example, here both Fragments use an onClick type of interface to communicate back to the Activity

 static interface OnClickedListener{
    public void buttonClicked(View v);
}

更好吗

A)创建一个单独的Interface类,并将其附加在两个Fragment中.例如片段1:

A) Create a separate Interface class and attach it within both Fragments. For example Fragment 1:

public class Fragment1 extends Fragment implements OnClickedListener{


private OnClickedListener clickedInterface;

public Fragment1() {
    // Required empty public constructor
}

@Override
public void buttonClicked(View v) {
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    this.clickedInterface = (OnClickedListener)activity;
}}

片段2:

public class Fragment2 extends Fragment implements OnClickedListener{

private OnClickedListener clickedInterface;

public Fragment2() {
    // Required empty public constructor
}

@Override
public void buttonClicked(View v) {
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    this.clickedInterface = (OnClickedListener)activity;
}

OR

B)创建特定于Fragment唯一的各个接口,并在MainActivity中实现这些接口,而不是如上所述的一个接口.谢谢.

B) Create individual Interfaces unique to the specific Fragment and implement those in the MainActivity instead of the one Interface like mentioned above. Thank you.

推荐答案

首先在工具界面中创建您的自定义片段.

First Create your custom fragment which is in implement interface.

    public class CustomFragment extends Fragment implements OnClickedListener{
        public OnClickedListener clickedInterface;

        @Override
        public void buttonClicked(View v) {
        }

        @Override
        public void onAttach(Activity activity) {
             super.onAttach(activity);
             this.clickedInterface = (OnClickedListener)activity;
        }
}

现在,您可以添加每个片段

Now, you can add in every fragment

(i)片段1

public class Fragment1 extends CustomFragment {
    ......
}

(ii)片段2

public class Fragment2 extends CustomFragment {
    ......
}

这篇关于多个片段的一个接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:23