Send data from Activity to Fragment already created

前端 未结 3 1680
北荒
北荒 2020-12-19 00:04

I only have found information about how to create a Fragment sending some data to it, but only in its instantiation with the constructor.

But I want to know if it is

3条回答
  •  醉梦人生
    2020-12-19 00:23

    The easiest way to do this is to define an interface in the Fragment and implement it within the activity. This link should provide a detailed example on how this can be accomplished. https://developer.android.com/training/basics/fragments/communicating.html

    I think the key part you are looking for is here:

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

    First try to retrieve the fragment by calling findFragmentById(R.id.fragment_id), and if it is not null you can make a call to the method you defined in your interface to send some data to it.

提交回复
热议问题