commit fragment from onLoadFinished within activity

后端 未结 3 1387
一向
一向 2020-12-31 10:57

I have an activity which loads a data list from the server using loader callbacks. I have to list out the data into a fragment which extends

SherlockListFra         


        
3条回答
  •  無奈伤痛
    2020-12-31 11:23

    As per the Android docs on the onLoadFinished() method:

    Note that normally an application is not allowed to commit fragment transactions while in this call, since it can happen after an activity's state is saved. See FragmentManager.openTransaction() for further discussion on this.

    https://developer.android.com/reference/android/app/LoaderManager.LoaderCallbacks.html#onLoadFinished(android.content.Loader, D)

    (Note: copy/paste that link into your browser... StackOverflow is not handling it well..)

    So you simply should never load a fragment in that state. If you really don't want to put the Loader in the Fragment, then you need to initialize the fragment in your onCreate() method of the Activity, and then when onLoadFinished occurs, simply call a method on your fragment.

    Some rough pseudo code follows:

    public class DummyFragment {
    
         public void setData(Object someObject) {
               //do stuff
         }
    
    public class DummyActivity extends LoaderCallbacks {
    
         public void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
    
               Fragment newFragment = DummyFragment.newInstance();
               FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
               ft.add(R.id.simple_fragment, newFragment).commit();
    
               getSupportLoaderManager.initLoader(0, null, this)
         }
    
         // put your other LoaderCallbacks here... onCreateLoader() and onLoaderReset()
    
         public void onLoadFinished(Loader loader, Object result) {
               Fragment f = getSupportLoaderManager.findFragmentById(R.id.simple_fragment);
               f.setData(result);
         } 
    
    
    

    Obviously, you'd want to use the right object.. and the right loader, and probably define a useful setData() method to update your fragment. But hopefully this will point you in the right direction.

    提交回复
    热议问题