如何将数据从片段发送到活动 [英] How to send data from fragment to activity

查看:66
本文介绍了如何将数据从片段发送到活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.
    }

这篇关于如何将数据从片段发送到活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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