如何使用接口在片段和活动之间进行通信? [英] How to use interface to communicate between fragment and activity?

查看:58
本文介绍了如何使用接口在片段和活动之间进行通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是想从MainActivity中调用Fragment方法.

I simply want to call a Fragment method from my MainActivity.

所以我尝试使用接口.

public interface MyInterface {
        void testMethod();
}

在我的片段(TestFragment.java)中,我实现了接口并覆盖了testMethod方法.

In my Fragment (TestFragment.java) I implement the interface and overrite the testMethod method.

@Override
public void testMethod() {
    Toast.makeText(getActivity(), "Test", Toast.LENGTH_LONG).show();
}

但是现在我想在调用onRewardedVideoCompleted get时从MainActivity调用此方法,但是我不确定该怎么做.我这样尝试过:

but now I want to call this method from my MainActivity as soon as the onRewardedVideoCompleted get's called, but I'm not sure how to do it. I tried it like this:

MyInterface myInterface = new TestFragment();
myInterface.testMethod();

但是这里我得到一个nullPointerException:

But here I get an nullPointerException:

试图调用虚拟方法'java.lang.String空对象引用上的android.content.Context.getPackageName()'这与Toast消息有关.

Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference Which reffers to the Toast message.

如何在我的MainActivity的接口中调用该方法而又没有得到NullPointerException?

How do I call the method from my Interface in my MainActivity without getting an NullPointerException?

谢谢

推荐答案

您需要为其创建界面,如下所示

You need to create the interface for it like below

public interface FilterValuePassInterface {

    public void onSelectedFilterValue(String name);
}

片段类应如下所示

class MyFragment extends Fragment implements FilterValuePassInterface {

   @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        try {
            ((YOUR_ACTIVITY) getActivity()).setOnDataListener(this);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }


    @Override
    public void onSelectedFilterValue(String name) {

    }
}

Activity 类中,您需要创建方法 setOnDataListener 并初始化片段,如下所示:

And inside the Activity class , you need to create the method setOnDataListener and initialise the fragment like below

 MyFragment myFragment;
    public void setOnDataListener(MyFragment myFragment) {

    this.myFragment = myFragment;

    }

在活动中,您可以通过任何点击或事件发送数据,您只需要从活动中调用此方法即可按如下所示的片段传输数据

Again inside the activity you can send the data from any click or event, you just need to call this method from the activity to transfer the data in fragment like below

    YOUR_CLICK.setOnClickListener(new OnClickListener() {

       public void onClick(View v) {
        // TODO Auto-generated method stub
        myFragment.onSelectedFilterValue("YOUR_MSG");

        }
        });

这篇关于如何使用接口在片段和活动之间进行通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆