如何将数据从片段发送到活动

问题描述:

在我的应用程序中,我在一个活动中有两个片段. 在其中一个片段中,我有数据,例如:

In my application I have two fragments in an activity. In one of the fragments I have data, such as :

String name = "Transporter";

我想将此名称发送到容器活动. 我该怎么做?请帮助我.

I want send this name to container activity. How can I do it? Please help me.

该片段将附加到您从中启动的活动.

The fragment will be attached to the activity which you launch from.

因此,您可以在活动中创建一个回调方法,可以使用活动上下文对象从片段中调用该方法.

Thus, you can create a callback method in your activity which can be called from fragment using the activity context object.

请参见以下代码段:

public class YourFragment extends Fragment{

       OnCallbackReceived mCallback;

// Implement this interface in your Activity.

public interface OnCallbackReceived {
    public void Update();
}

在您的片段中:

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    try {
        mCallback = (OnCallbackReceived) activity;
    } catch (ClassCastException e) {

    }
}

    // You can Call the event from fragment as mentioned below
    // mCallback is the activity context. 
    mCallback.Update();

活动:

public class MainActivity extends Activity
        implements YourFragment.OnCallbackReceived {

    // Implemented method.
    public override void Update() {
        // Write your logic here.
    }