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

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

问题描述

我正在尝试实现片段到活动的交流.

Im trying to implement fragment to activity communication.

通过 Android开发人员文档进行操作,在该文档中传递了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();
}

现在您有一个实现ICommunicationActivity名称MainActivity,那么它必须具有实现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天全站免登陆