代码之家  ›  专栏  ›  技术社区  ›  sergio

将数据从活动发送到已创建的片段

  •  13
  • sergio  · 技术社区  · 7 年前

    先前创建的片段。

    3 回复  |  直到 7 年前
        1
  •  16
  •   Will Tang    7 年前

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

    活动代码:

    Activity's Code

    片段代码:

    Fragment's Code

        2
  •  3
  •   Karim    7 年前

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

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

    Bundle bundle = this.getArguments();
    if (bundle != null) {
            int myInt = bundle.getInt(key, defaultValue);
    }
    
        3
  •  2
  •   Zach Sogolow    7 年前

    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\u id)来检索片段,如果它不为null,则可以调用在接口中定义的方法来向其发送一些数据。