简体   繁体   中英

Recommended way to pass data from activity to viewPager fragment

I have an activity that performs network operation, and on success, it needs to send data to view pager fragment .

So this is my structure.

Activity -> Home Fragment -> ViewPager [Fragment#1, Fragment#2]

Now the issue is that i can send data from Activity to Home Fragment , but i am unable to send data to View Pager Fragment , as activity does not have any direct connection with it.

To Fix this, I have taken network call from activity to fragment, and once i get response from service call , i pass data to viewPager fragment from Home Fragment .

This is working fine, and giving me desired result, but i am little confused if this is the right approach.

or there is some other recommended approach available that i can use, and pass data from activity to child fragment, or view Pager fragment, whose reference is not directly available to activity.

I would look at the new Android Architecture Components, specifically ViewModel and LiveData . https://developer.android.com/topic/libraries/architecture/viewmodel

The ViewModel class is designed to store and manage UI-related data in a lifecycle conscious way.

You can create a shared view model that can be accessed by the activity and any fragment in that activity.

Example from the link:

public class SharedViewModel extends ViewModel {
    private final MutableLiveData<Item> selected = new MutableLiveData<Item>();

    public void select(Item item) {
        selected.setValue(item);
    }

    public LiveData<Item> getSelected() {
        return selected;
    }
}


public class MasterFragment extends Fragment {
    private SharedViewModel model;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        itemSelector.setOnClickListener(item -> {
            model.select(item);
        });
    }
}

public class DetailFragment extends Fragment {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedViewModel model = ViewModelProviders.of(getActivity()).get(SharedViewModel.class);
        model.getSelected().observe(this, item -> {
           // Update the UI.
        });
    }
}

Notice that both fragments use getActivity() when getting the ViewModelProvider. As a result, both fragments receive the same SharedViewModel instance, which is scoped to the activity.

For your example, this avoids passing data down the hierarchy from activity to fragment then child fragment, they can all reference SharedViewModel .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM