将对象从片段传递到活动 [英] Passing Object from Fragment to Activity

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

问题描述

问题:如何将对象从片段传递到活动(应活动的请求).

Question: How do I pass objects from fragment to activity (on request from activity).

背景:我正在使用Android Studio,并已通过新建Android活动"向导设置了一个新的选项卡式活动.然后,我定义了5个片段,每个片段包含不同的输入集(编辑文本等). 然后,每个输入表单都会填充一个自定义对象,以便可以将其传递到选项卡宿主活动. 然后,一旦在任务栏上按下添加按钮",我将把这些对象保存在数据库中(这是从片段中取出对象的位置).但是,我找不到将对象从片段传递到活动的方法. 以前,我通过使用和调用'getObject()'方法在活动之间传递对象,这似乎不适用于片段.

Background: I am using Android Studio and have set up a new tabbed activity from the New Android Activity wizard. I have then defined 5 fragments that each contain different sets of inputs (edit texts and so on). Each input form then populates a custom object so that it can be passed to the tab host activity. I will then save the objects in a database once an 'Add button' is pressed on the task bar (this is where the objects should be taken in from fragments). However I cannot find a way to pass the objects from the fragments to the activity. Previously I have passed objects between activities by using and calling a 'getObject()' method, this doesn't seem to work for the fragments.

我的片段当前没有'onAttach'方法,我不太确定该怎么做.

My fragments do not currently have an 'onAttach' method, I'm not too sure what this does.

在此先感谢您的帮助.

Thanks in advance for any help.

推荐答案

您可以有一个接口:

public interface MyInterface {
    void doSomethingWithData(Object data);
}

然后在活动课中:

public class MyActivity extends Activity implements MyInterface {
    ...
    public void doSomethingWithData(Object data) {
        // save your data in database
    }
    ...
}

及其片段:

public class MyFragment extends Fragment {
    ...
    private MyInterface listener;
    ...
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof MyInterface) {
            listener = (MyInterface) context;
        }
    }

    @Override
    public void onDetach() {
        listener = null;
        super.onDetach();
    }
    ...
    // Somewhere in code .. where you want to send data to the activity
    listener.doSomethingWithData(data);
    ...
}

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

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