Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
447 views
in Technique[技术] by (71.8m points)

android - Fragment activity communication by passing Context object to onAttach()

Im trying to implement fragment to activity communication.

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

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

Edit :

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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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();
}

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();
}

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();

Here , TestFragment must be hold on MainActivity.

My related answer with source is here Thats it :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...