如何在活动和片段之间传递对象 [英] how to pass object between activity and fragment

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

问题描述

请给我一些有关如何在片段和活动之间传递对象的建议.

Please give me some suggestions how to pass object between fragment and activity.

在我的项目中,有一个FragmentActivity可以显示和编辑客户资料.此活动中将包含多个选项卡,以显示联系信息,地址...客户信息将作为活动中的一类预先加载.我的问题是如何将该对象传递给每个片段或选项卡?更新后,如何返回活动状态?

In my project, there is one FragmentActivity to show and edit customer profile. Multiple tabs will be contained in this activity to show contact info, address... The customer info will be preload as one class in the activity. My question is how could I pass this object to each fragment or tab? Once updated, how could I pass back to activity?

我是否必须在我的客户类中实现Parcelable接口才能通过捆绑销售商品?

Do I must to implement the Parcelable interface in my customer class to pass by bundle?

每个选项卡都会动态创建,是否可以直接获取片段实例来修改视图?如果是,一旦切换选项卡,片段会被销毁吗?

Each tab will be dynamic created, is possible to get the fragment instance to modify view directly? If yes, once tab switch, is fragment destroyed?

谢谢

迈伦

推荐答案

毫无疑问:最佳解决方案是从片段中调用活动方法:

No doubt: best solution is to call an activity method from the fragment:

这里有一个位图对象的例子.

Here an example with a Bitmap Object.

活动中:

定义您的方法:

public Bitmap getMyBitmap() {
    return myBitmap;
}

在片段中:

1-定义您的活动

private Activity_Main myActivity;

2-关联您的活动

@Override
public void onAttach(Activity myActivity) {
    super.onAttach(myActivity);
    this.activity= (Activity_Main) myActivity;
}

3-调用您的方法!

myActivity.getMyBitmap()

快速简便!

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

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