How to send data from Activity to Fragment

前端 未结 5 1855
盖世英雄少女心
盖世英雄少女心 2020-12-05 21:44

I know there are many topics about this here. I have also read documentation many times but I can\'t find the best way to pass data from activity to fragment.

I want

5条回答
  •  情歌与酒
    2020-12-05 21:58

    Find fragment in Activity onCreate and set data to a method you write in your fragment:

            ExampleFragment rf =  (ExampleFragment) getSupportFragmentManager().findFragmentById(R.id.exampleFragment);
    
        if(rf!=null){
        rf.setExample(currentExample);
        }
    

    "CurrentExample" is whatever you want to send in to your "setExample" method in your fragment.

    public void setExample(ExampleObject currentExample){
    
        currentExampleInFragment = currentExample;
    
    }
    

    You can use the data in onActivityCreated method of Fragment.

    Not sure is this is a good solution or not, but I found it the easiest one for passing objects.

提交回复
热议问题