Proper way to give initial data to fragments?

前端 未结 1 336
一生所求
一生所求 2020-12-04 14:03

So I\'ve learned that I need an empty constructor in order for my fragments not to crash on reinitialization. My problem is that I use lists of data for my fragments when th

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

    So what would be a good way to start new fragments with a list of data.

    Use the factory pattern and the "arguments" Bundle, such as:

    package com.commonsware.empublite;
    
    import android.os.Bundle;
    
    public class SimpleContentFragment extends AbstractContentFragment {
      private static final String KEY_FILE="file";
    
      protected static SimpleContentFragment newInstance(String file) {
        SimpleContentFragment f=new SimpleContentFragment();
    
        Bundle args=new Bundle();
    
        args.putString(KEY_FILE, file);
        f.setArguments(args);
    
        return(f);
      }
    
      @Override
      String getPage() {
        return(getArguments().getString(KEY_FILE));
      }
    }
    

    If you are retaining your fragment instance, you should be able to get away with just using ordinary setters to put stuff in data members. The "arguments" Bundle is retained as part of configuration changes, so for non-retained instances, this is the way to ensure your setup data is retained if the user rotates the screen, etc.

    0 讨论(0)
提交回复
热议问题