在MainActivity中创建的fragment对象可以作为intent extra传递给其他activity吗?



我有一个类WeatherFragment扩展Fragment类。我在启动器活动中创建了一个实例,并在布局中对其进行了膨胀。我是否有可能将片段对象作为一个额外的意图发送到我的项目中的其他活动,而不是创建一个新的WeatherFragment实例?

这个没有代码。这只是一个面试问题。

我认为你可以,但是这不会很好。我快速搜索了一下这个问题,得到的答案是:

你不会。最多,您将遵循@核糖的答案——通过一个额外的标记传递到活动中,以指示要创建的片段集。

你的问题不太具体。这个问题是特定于OP想要的,但也许其中一个答案可以帮助你。

注:如果你想实验,你可以让你的WeatherFragment实现Parcelable。然后通过意图将它从一个活动传递到另一个活动。这个答案会告诉你怎么做,你可以这样做(修改为扩展Fragment类)

public class WeatherFragment extends implements Parcelable {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment, container, false);
    }
    /* everything below here is for implementing Parcelable */
    // 99.9% of the time you can just ignore this
    public int describeContents() {
        return 0;
    }
    // write your object's data to the passed-in Parcel
    public void writeToParcel(Parcel out, int flags) {
        //code
    }
    // this is used to regenerate your object. All Parcelables must have a CREATOR that implements these two methods
    public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {
        public MyParcelable createFromParcel(Parcel in) {
            return new MyParcelable(in);
        }
        public MyParcelable[] newArray(int size) {
            return new MyParcelable[size];
        }
    };
    // example constructor that takes a Parcel and gives you an object populated with it's values
    private MyParcelable(Parcel in) {
        //code
    }
    //other methods
}

然后,再从答案中,你可以这样使用:

Intent intent = new Intent();
intent.putExtra(KEY_EXTRA, weatherFragment);

再次从答案中(你真的应该读一下这个答案),你得到如下:

Intent intent = getIntent();
WeatherFragment weatherFragment = (WeatherFragment) intent.getParcelableExtra(MainActivity.KEY_EXTRA);

我还没有测试过这个所以我不确定它是否会工作

在不同的活动之间你不能,因为Fragment不实现Serializable或Parcelable。

当然你可以让你的Fragment实现这些接口,但这样你实际上不会传递Fragment,只是Fragment的一些状态,然后你自己序列化。

在同一个活动中,如果你在onSaveState()中使用FragmentManager.putFragment()和onCreate()中的getFragment(),你可以在活动重新创建时拥有你的片段。

可能,但我不建议这么做。但是您可以通过使用findFragmentByIdfindFragmentByTag来获得片段对象。

最新更新