Send data from activity to fragment in Android

前端 未结 20 2710
悲哀的现实
悲哀的现实 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:34

    Very old post, still I dare to add a little explanation that would had been helpful for me.

    Technically you can directly set members of any type in a fragment from activity.
    So why Bundle?
    The reason is very simple - Bundle provides uniform way to handle:
    -- creating/opening fragment
    -- reconfiguration (screen rotation) - just add initial/updated bundle to outState in onSaveInstanceState()
    -- app restoration after being garbage collected in background (as with reconfiguration).

    You can (if you like experiments) create a workaround in simple situations but Bundle-approach just doesn't see difference between one fragment and one thousand on a backstack - it stays simple and straightforward.
    That's why the answer by @Elenasys is the most elegant and universal solution.
    And that's why the answer given by @Martin has pitfalls

提交回复
热议问题