Android Refresh A Fragment List From Its Parent Activity


Answer :

You can easily achieve this using INTERFACE

MainActivity.java

public class MainActivity extends Activity {      public FragmentRefreshListener getFragmentRefreshListener() {         return fragmentRefreshListener;     }      public void setFragmentRefreshListener(FragmentRefreshListener fragmentRefreshListener) {         this.fragmentRefreshListener = fragmentRefreshListener;     }      private FragmentRefreshListener fragmentRefreshListener;      @Override     public void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);           Button b = (Button)findViewById(R.id.btnRefreshFragment);          b.setOnClickListener(new View.OnClickListener() {             @Override             public void onClick(View view) {                 if(getFragmentRefreshListener()!=null){                     getFragmentRefreshListener().onRefresh();                 }             }         });       }       public interface FragmentRefreshListener{         void onRefresh();     }  } 

MyFragment.java

public class MyFragment extends Fragment {      @Override     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {         View v = null; // some view          /// Your Code           ((MainActivity)getActivity()).setFragmentRefreshListener(new MainActivity.FragmentRefreshListener() {             @Override             public void onRefresh() {                  // Refresh Your Fragment             }         });           return v;     } } 

  • Just make your update/refresh method public and call it from your Activity.

OR

  • Use LocalBroadcastManager or EventBus to send event from your Activity, and by subscribing to this event in a Fragment - react to it and call refresh/update method.

Your activity can call methods in the fragment by acquiring a reference to the Fragment.

(1) Provide a tag when you add your fragment.

transaction.add(R.id.fragment_container, myFragment, "myfragmentTag"); 

(2) In your hosting activity you can find the fragment and have access to it's methods.

FragmentManager fm = getSupportFragmentManager(); myFragment f = (myFragment) fm.findFragmentByTag("myfragmentTag"); f.refreshAdapter() 

(3) refreshAdapter() could now call adapter.notifyDataSetChanged().

This is one of the recommended ways to communicate up to a fragment. The interface implementation is mainly for communicating back to the activity.


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?