Dynamically updating a fragment

后端 未结 1 1030
余生分开走
余生分开走 2020-12-10 09:23

I basically have a MainActivity that has multiple tabs. Each tab is a ShowListFragment and it extends Fragment. Now, each tab contains data that I fetch from a database. I h

相关标签:
1条回答
  • 2020-12-10 10:14

    Since the fragments can access the activity easily enough with getActivity(), I would make the activity be the central hub for dispatching updates.

    It sounds like you already have the persistence part handled with the database and all you need is some update events. So here goes:

    1. Define a listener interface. I usually do this as an inner interface within the activity:

          public interface DataUpdateListener {
              void onDataUpdate();
          }
      
    2. Add a data structure to your activity to keep track of listeners:

          private List<DataUpdateListener> mListeners;
      

      Don't forget to initialize in the constructor:

              mListeners = new ArrayList<>();
      
    3. Add the register/unregister methods to the activity:

          public synchronized void registerDataUpdateListener(DataUpdateListener listener) {
              mListeners.add(listener);
          }
      
          public synchronized void unregisterDataUpdateListener(DataUpdateListener listener) {
              mListeners.remove(listener);
          }
      
    4. Add the event method to your activity:

          public synchronized void dataUpdated() {
              for (DataUpdateListener listener : mListeners) {
                  listener.onDataUpdate();
              }
          }
      
    5. Have your fragments implement DataUpdateListener:

      public class MyFragment extends Fragment implements DataUpdateListener {
      

      and implement the method

          @Override
          public void onDataUpdate() {
              // put your UI update logic here
          }
      
    6. Override onAttach() and onDestroy() in the fragments to register/unregister:

          @Override
          public void onAttach(Activity activity) {
              super.onAttach(activity);
              ((MainActivity) activity).registerDataUpdateListener(this);
          }
      
          @Override
          public void onDestroy() {
              super.onDestroy();
              ((MainActivity) getActivity()).unregisterDataUpdateListener(this);
          }
      
    7. Fire the event in your fragment's UI update event:

          @Override
          public void onClick(DialogInterface dialog, int listIndex) {
              database.add(listIndex,object);
              database.remove(listIndex,object);
              ((MainActivity) getActivity()).dataUpdated();
          }
      
    0 讨论(0)
提交回复
热议问题