How to send data from Activity to Fragment

前端 未结 5 1853
盖世英雄少女心
盖世英雄少女心 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 22:09

    "send data from Activity to Fragment"

    Activity:

            Bundle bundle = new Bundle();
            bundle.putString("message", "Alo Stackoverflow!");
            FragmentClass fragInfo = new FragmentClass();
            fragInfo.setArguments(bundle);
            transaction.replace(R.id.fragment_single, fragInfo);
            transaction.commit();
    

    Fragment:

    Reading the value in the fragment

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            Bundle bundle = this.getArguments();
            String myValue = bundle.getString("message");
            ...
            ...
            ...
            }
    

    or

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            String myValue = this.getArguments().getString("message");
            ...
            ...
            ...
            }
    

提交回复
热议问题