Passing an Object from an Activity to a Fragment

前端 未结 8 2043
别那么骄傲
别那么骄傲 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:28

    Create a static method in the Fragment and then get it using getArguments().

    Example:

    public class CommentsFragment extends Fragment {
      private static final String DESCRIBABLE_KEY = "describable_key";
      private Describable mDescribable;
    
      public static CommentsFragment newInstance(Describable describable) {
        CommentsFragment fragment = new CommentsFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable(DESCRIBABLE_KEY, describable);
        fragment.setArguments(bundle);
    
        return fragment;
      }
    
      @Override
      public View onCreateView(LayoutInflater inflater,
          ViewGroup container, Bundle savedInstanceState) {
    
        mDescribable = (Describable) getArguments().getSerializable(
            DESCRIBABLE_KEY);
    
        // The rest of your code
    }
    

    You can afterwards call it from the Activity doing something like:

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    Fragment fragment = CommentsFragment.newInstance(mDescribable);
    ft.replace(R.id.comments_fragment, fragment);
    ft.commit();
    

提交回复
热议问题