将对象从片段传递到活动

编程入门 行业动态 更新时间:2024-10-24 21:30:29
本文介绍了将对象从片段传递到活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

将对象从片段传递到活动

本文发布于:2023-10-07 17:31:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1470034.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:片段   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!