Here I no longer detail the more conventional way of writing, such as static variables, static methods, persistence, application global variables, sending and receiving broadcasts, and so on.
First, we introduce the use of handler to achieve fragment interaction with the activity.
In the first step, we need to define a method in activity to set the handler object.
Public void SetHandler (Handler Handler) { = Handler;}
In the second step, we get fragment activity in the callback function Onattach () in fragment, and call SetHandler method, set handler. The handler is defined in fragment to receive messages that interact with fragment.
@Override Public voidOnattach (activity activity) {Super.onattach (activity); Mactivity=(mainactivity) activity; Mactivity.sethandler (Mhandler);} PublicHandler Mhandler =NewHandler () { Public voidhandlemessage (android.os.Message msg) {Switch(msg.what) { Case 1: Text.settext (String) msg.obj); Break; } };};
We can then send a message in the activity to interact with the Hanlder in fragment.
Public void Inter (view view) { new Message (); = Edit.gettext (). toString (); 1 ; Mhandler.sendmessage (msg);}
I wrote a demo to share with you, link address: http://download.csdn.net/detail/huangyabin001/7559807
Click to download Demo
Android fragment several ways to interact with your activity