如何将变量从 Activity 传递到 Fragment,并将其传回? [英] How to pass a variable from Activity to Fragment, and pass it back?

查看:42
本文介绍了如何将变量从 Activity 传递到 Fragment,并将其传回?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在制作一个 android 应用程序,我想在活动和片段之间传递一个日期.我的活动有一个按钮,可以打开片段:DatePickerFragment.

I am currently making an android app, and I want to pass a date between activity and fragment. My activity has a button, which opens the fragment: DatePickerFragment.

在我的活动中,我显示了一个日期,我想用片段修改它.所以我想将日期传递给日期选择器,并将其发送回活动.

In my activity I show a date, which I want to modify with the fragment. So I want to pass the date to the datepicker, and send it back to the activity.

我尝试了很多解决方案,但都没有奏效.最简单的方法是传递一个参数,但这不能用片段来完成.

I've tried a lot of solutions, but none are working. The easy way would pass an argument, but this can't be done with fragments.

推荐答案

要将信息传递给片段,在创建片段时设置参数,稍后可以在方法 onCreate 或您片段的 onCreateView.

To pass info to a fragment , you setArguments when you create it, and you can retrieve this argument later on the method onCreate or onCreateView of your fragment.

在片段的 newInstance 函数上,添加要发送给它的参数:

On the newInstance function of your fragment you add the arguments you wanna send to it:

/**
 * Create a new instance of DetailsFragment, initialized to
 * show the text at 'index'.
 */
public static DetailsFragment newInstance(int index) {
    DetailsFragment f = new DetailsFragment();
    // Supply index input as an argument.
    Bundle args = new Bundle();
    args.putInt("index", index);
    f.setArguments(args);
    return f;
}

然后在方法 onCreateonCreateView 的片段内,您可以检索这样的参数:

Then inside the fragment on the method onCreate or onCreateView you can retrieve the arguments like this:

Bundle args = getArguments();
int index = args.getInt("index", 0);

如果您现在想从您的片段与您的活动(发送或不发送数据)进行通信,您需要使用接口.您可以执行此操作的方式在片段之间通信的文档教程中得到了很好的解释.因为所有片段都通过活动相互通信,所以在本教程中,您可以看到如何将数据从实际片段发送到他的活动容器,以在活动中使用此数据或将其发送到您的活动包含的另一个片段.

If you want now communicate from your fragment with your activity (sending or not data), you need to use interfaces. The way you can do this is explained really good in the documentation tutorial of communication between fragments. Because all fragments communicate between each other through the activity, in this tutorial you can see how you can send data from the actual fragment to his activity container to use this data on the activity or send it to another fragment that your activity contains.

文档教程:

http://developer.android.com/training/basics/fragments/沟通.html

这篇关于如何将变量从 Activity 传递到 Fragment,并将其传回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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