Send data from activity to fragment in Android

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

    I ran into a similar issue while using the latest Navigation architecture component. Tried out all the above-mentioned code with passing a bundle from my calling activity to Fragment.

    The best solution, following the latest development trends in Android, is by using View Model (part of Android Jetpack).

    Create and Initialize a ViewModel class in the parent Activity, Please note that this ViewModel has to be shared between the activity and fragment.

    Now, Inside the onViewCreated() of the fragment, Initialize the Same ViewModel and setup Observers to listen to the ViewModel fields.

    Here is a helpful, in-depth tutorial if you need.

    https://medium.com/mindorks/how-to-communicate-between-fragments-and-activity-using-viewmodel-ca733233a51c

提交回复
热议问题