Passing an Object from an Activity to a Fragment

前端 未结 8 2034
别那么骄傲
别那么骄傲 2020-11-27 10:55

I have an Activity which uses a Fragment. I simply want to pass an object from this Activity to the Fragment.

How

8条回答
  •  醉梦人生
    2020-11-27 11:22

    Get reference from the following example.

    1. In fragment: Create a reference variable for the class whose object you want in the fragment. Simply create a setter method for the reference variable and call the setter before replacing fragment from the activity.

     MyEmployee myEmp;
     public void setEmployee(MyEmployee myEmp)
     {
         this.myEmp = myEmp;
     }
    

    2. In activity:

       //we need to pass object myEmp to fragment myFragment
    
        MyEmployee myEmp = new MyEmployee();
    
        MyFragment myFragment = new MyFragment();
    
        myFragment.setEmployee(myEmp);
    
        FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
        ft.replace(R.id.main_layout, myFragment);
        ft.commit();
    

提交回复
热议问题