如何从活动传递一个变量片段,并传回?变量、片段

2023-09-12 00:50:50 作者:岁月靜好,足矣!

我目前做一个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.

在我的活动我秀的日期,这是我想要的片段进行修改。所以,我想通过日期的日期选择器,并将其发送回的活动。

On 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 alot of solutions, but none are working. The easy way would be pass an argument, but this can't be done with fragments.

感谢

推荐答案

要传递信息,以片段,当您创建它,你可以在方法以后检索该参数的onCreate您setArguments或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.

在你的片段中的n​​ewInstance功能添加你想发送给它的参数:

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

然后在方法的onCreate或片段内onCreateView可以检索这样的观点:

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/communicating.html