通过将 Context 对象传递给 onAttach() 来进行片段活动通信 [英] Fragment activity communication by passing Context object to onAttach()

查看:19
本文介绍了通过将 Context 对象传递给 onAttach() 来进行片段活动通信的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现片段到活动的通信.

Im trying to implement fragment to activity communication.

浏览了 android developer 文档,其中传递了 Activity 对象以 onAttach 生命周期并设置 Fragment-Activity 通信.

Went through android developer doc where an Activity object is passed to onAttach life cycle and set up the Fragment-Activity communication.

这个文档要求传递 Context 对象而不是 Activity.我在生命周期方法 onAttach 中将所有 Activity 对象替换为 Context 对象.但是它在从 Fragment 调用接口的方法时抛出了 NullPointerException.

This documentation asks to pass Context object instead of Activity. I replaced all the Activity objects by Context objects in the life cycle method onAttach. But it is throwing a NullPointerException while calling the method of the interface from Fragment.

@Override
public void onAttach(Context context) {
    super.onAttach(context);
    try {
        colourChangerInterface = (ColourChangerInterface) context;
    }
    catch (Exception exp){
        System.out.println("error!");
    }
}

任何人都可以举一个新方式用法的小例子吗?谢谢

Can anyone please give a small example of the usage in the new way ? Thanks

编辑:

找到这个链接,其中有详细讨论问题.问题是因为 API 'onAttach()' 损坏;当传递 Context 对象时,它根本不会被调用.

Found this link where detail discussion is there on the same issue. The issue is because of the broken API 'onAttach()'; it doesn't get called at all when Context object is passed.

从上述链接中找到的一个简单快捷的解决方案是将代码从 onAttach 移动到 onCreate.

A simple and quick solution found from the above link is to move the code from onAttach to onCreate.

推荐答案

这里有一个小例子,将描述ActivityFragment 之间的通信.假设您有一个接口 ICommunication.这在下面给出:

Here is a small example that will describe you the communication between Activity and Fragment. Suppose you have a Interface ICommunication. This is given below:

public interface ICommunication {
    public void testMethod();
}

现在你有一个 Activity 名称 MainActivity 实现了 ICommunication 然后它必须实现了方法 testMethod().这个方法会像这样:

Now you have a Activity name MainActivity that implements ICommunication then it must have implements the method testMethod(). This method will like this:

@Override
    public void testMethod() {
    Toast toast = Toast.makeText(getActivity(), "It's called from Fragment", Toast.LENGTH_SHORT).show();
}

现在,假设这个 MainActivity 属于一个 Fragment 名称 TestFragment .如果你想从 TestFragment 访问 MainActivity 的 testMethod() 那么你可以简单地使用这种方式调用:

Now, suppose this MainActivity belongs a Fragment name TestFragment . If you want to access testMethod() of MainActivity from TestFragment then you can simply call using this way :

((ICommunication)getActivity()).testMethod();

这里,TestFragment 必须保持在 MainActivity 上.

Here , TestFragment must be hold on MainActivity.

我与来源的相关答案是这里就是这样:)

My related answer with source is here Thats it :)

这篇关于通过将 Context 对象传递给 onAttach() 来进行片段活动通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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