可包裹对象从android活动传递到片段 [英] Parcelable object passing from android activity to fragment

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

问题描述

我正在尝试将可实现Parcelable 实现的对象从活动传递到片段.我知道如何从一个活动传到另一个活动.我只想尝试这个.但是当我收到对象时,它总是收到 null .我该如何解决这个问题?

I'm trying to pass an object that implements Parcelable from an activity to a fragment. I know how to pass from activity to activity. I just want to try this. But when I received the object it always receivednull. How can I resolve this problem?

currentObject 是实现Parcelable的类的对象实例

currentObject is the object instance of the class which implements Parcelable

ContentMainFragment 是Fragment类

ContentMainFragment is the Fragment class

在活动中

   Fragment fragment = new ContentMainFragment();
   Bundle bundle = new Bundle();
   bundle.putParcelable("SampleObject", currentObject);
   fragment.setArguments(bundle);

在片段中

Bundle bundle = this.getArguments();
if (bundle != null) {
            currentObject = bundle.getParcelable("SampleObject");
link = currentObject.getLink();
}

谢谢.

推荐答案

尝试一下

首先,改变一些小东西.

First, change some small things.

MainActivity.java

// 1. Parse the object to the fragment as a bundle;
ContentMainFragment contentMainFragment = new ContentMainFragment();

Bundle bundle = new Bundle();
bundle.putParcelable("SampleObject", currentObject);
contentMainFragment.setArguments(bundle);

// 2. Commit the fragment.
getSupportFragmentManager().beginTransaction()
        .add(R.id.fragment_container, contentMainFragment).commit();

ContentMainFragment.java

// 1. Get the object in onCreate();
if (getArguments() != null) { 
    link = getArguments().getParcelable("SampleObject").getLink(); 
}

第二,您的方法似乎没有问题,然后再次检查您是否在Activity中解析了有效对象(currentObject).

Second, it doesn't seem there is something wrong with your approach, then double check if you are parsing a valid object (currentObject) in the Activity.

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

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