Send data from activity to fragment in Android

前端 未结 20 2704
悲哀的现实
悲哀的现实 2020-11-21 05:13

I have two classes. First is activity, second is a fragment where I have some EditText. In activity I have a subclass with async-task and in method doInBa

20条回答
  •  无人及你
    2020-11-21 05:40

    I´ve found a lot of answers here @ stackoverflow.com but definitely this is the correct answer of:

    "Sending data from activity to fragment in android".

    Activity:

            Bundle bundle = new Bundle();
            String myMessage = "Stackoverflow is cool!";
            bundle.putString("message", myMessage );
            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 just

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

提交回复
热议问题