【问题标题】:Pass parameter from activity to fragment将参数从活动传递到片段
【发布时间】:2015-10-18 14:08:52
【问题描述】:

我有一个调用 Web 服务的活动,我想将这些结果传递给片段。很明显web服务是被AsyncTask调用的,所以fragment在得到结果之前就被加载了。

如何在收到时将这个参数从活动的 AsyncTask 传递给片段?

【问题讨论】:

    标签: android android-fragments android-activity android-asynctask


    【解决方案1】:

    您可以在 Fragment 中实现一个方法,并在需要时调用它。有关 Activity 和 Fragment 之间的双向通信,请参阅http://developer.android.com/training/basics/fragments/communicating.html

    【讨论】:

      【解决方案2】:

      在您的片段中设置捆绑包。

      Bundle args = new Bundle();
      args.putInt("id",value);    
      Fragment newFragment = new Fragment();
      newFragment.setArguments(args);
      

      在您的片段中获取捆绑包

      Bundle b = getArguments();
      String s = b.getInt("id");
      

      【讨论】:

        【解决方案3】:

        您可以将 AsyncTask 移动到片段中。

        但如果您希望保持当前设置,则应在初始化时保存 Fragment 引用,并在 Fragment 中创建一个将新数据作为参数的公共函数。

        所以活动代码可能如下所示:

        MyFragment fragment = new MyFragment();
        getFragmentManager().beginTransaction().replace(android.R.id.content, fragment).commit();
        

        然后你可以调用:

        fragment.updateData(myNewData);
        

        确保进行适当的空值检查,以确保安全。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多