将对象从片段传递到活动

时间:2016-01-29 18:47:36

标签: android object android-fragments android-activity

问题:如何将对象从片段传递到活动(根据活动请求)。

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

我的片段目前没有' onAttach'方法,我不太清楚这是做什么的。

提前感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

你可以有一个界面:

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

答案 1 :(得分:1)

活动包含碎片的实例,因此当您按下“添加”按钮时,您可以从碎片中收集数据。

例如,从TabActivity:

int cards = fragment1.getCards();
String name = fragment2.getUserName();

只需在片段中创建公共方法。

答案 2 :(得分:0)

您可以在该对象的decalare getter setter中创建一个DataManger Singelton类,并在整个项目中使用它。