【问题标题】:Send data from Activity to Fragment already created将数据从 Activity 发送到已创建的 Fragment
【发布时间】:2017-07-06 23:33:50
【问题描述】:

我只找到了有关如何创建向其发送一些数据的 Fragment 的信息,但仅在其使用构造函数的实例化中。

但我想知道是否可以将一些数据(例如,两个 Double 对象)从 Activity 发送到 Fragment,而无需创建 Fragment 的新实例。

之前创建的片段。

【问题讨论】:

    标签: android android-fragments android-activity interaction


    【解决方案1】:

    只需在 Fragment 中添加一个您想要接收参数的方法,然后在 Activity 中调用该方法。

    活动代码:



    片段的代码:

    【讨论】:

    • 请问,这种情况下如何声明片段?需要扩展 Fragment 类吗?
    • 当然,扩展了 Fragment 类。 @davidmlee
    【解决方案2】:

    您可以通过如下捆绑传输任何数据:

    Bundle bundle = new Bundle();
    bundle.putInt(key, value);
    your_fragment.setArguments(bundle);
    

    然后在您的 Fragment 中,使用以下命令检索数据(例如在 onCreate() 方法中):

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

    【讨论】:

      【解决方案3】:

      最简单的方法是在 Fragment 中定义一个接口并在 Activity 中实现它。此链接应提供有关如何完成此操作的详细示例。 https://developer.android.com/training/basics/fragments/communicating.html

      我认为您正在寻找的关键部分在这里:

      ArticleFragment articleFrag = (ArticleFragment)
            getSupportFragmentManager().findFragmentById(R.id.article_fragment);
      
      if (articleFrag != null) {
          // If article frag is available, we're in two-pane layout...
      
          // Call a method in the ArticleFragment to update its content
          articleFrag.updateArticleView(position);
      } else {
          // Otherwise, we're in the one-pane layout and must swap frags...
      
          // Create fragment and give it an argument for the selected article
          ArticleFragment newFragment = new ArticleFragment();
          Bundle args = new Bundle();
          args.putInt(ArticleFragment.ARG_POSITION, position);
          newFragment.setArguments(args);
      
          FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
      
          // Replace whatever is in the fragment_container view with this fragment,
          // and add the transaction to the back stack so the user can navigate back
          transaction.replace(R.id.fragment_container, newFragment);
          transaction.addToBackStack(null);
      
          // Commit the transaction
          transaction.commit();
      }
      

      首先尝试通过调用 findFragmentById(R.id.fragment_id) 来检索片段,如果它不为 null,则可以调用您在接口中定义的方法向其发送一些数据。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-07-23
        • 2013-09-27
        • 2018-04-14
        • 1970-01-01
        • 1970-01-01
        • 2023-03-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多