在menuItemclick上从Activity(Activity-> Fragment-> Fragment)发送数据到Fragment of Fragment

时间:2017-11-02 09:01:04

标签: android android-fragments fragment

我正在尝试将MainActivity中的数据(在MenuItem上单击)发送到其子片段的片段。

我已经展示了一张图片以便更好地理解。

enter image description here

我想要在MainActivity菜单点击时从MainActivity在DayFragment中触发事件。

我知道在创建片段时无法发送。

理解这个想法的任何想法(或)代码都会有所帮助。

伙计们,否定投票既不会帮助你也不会帮助你。

我将详细解释。

我将在菜单项上单击MainActivity上显示一个datepicker对话框片段。我需要从MainActivity传递日期 - > calendarfragment - > dayfragment。

我想将dayfragment中的日期转换为其他进程。多数民众赞成。

2 个答案:

答案 0 :(得分:1)

在Fragment中创建一个公共方法,Activity将调用项目选择。

从那个公共方法,使用ChildFragment的实例,调用ChildFragment中的另一个公共方法来实现魔法!

您可以使用Fragment.setTarget(Fragment fragment, int requestCode);,以防万一

答案 1 :(得分:0)

使用捆绑。以下是一个例子:

Fragment fragment = new Fragment(); // replace your custom fragment class 
Bundle bundle = new Bundle();
FragmentTransaction fragmentTransaction = getSupportFragmentManager(). beginTransaction();
bundle.putString("key","value"); // use as per your need
fragment.setArguments(bundle);
fragmentTransaction.addToBackStack(null);
fragmentTransaction.replace(viewID,fragment);
fragmentTransaction.commit();

Bundle为许多数据类型设置了方法。

然后在片段中,使用以下内容检索数据(例如onCreate()方法)

Bundle bundle = this.getArguments();
if (bundle != null) {
        int myInt = bundle.getInt(key, defaultValue);
}