实例化片段的最佳方法?

Best way to instantiate a fragment?

方法一

public static MyFragment newInstance(int index) {

    MyFragment f = new MyFragment();

    Bundle args = new Bundle(1);

    args.putInt("index", index);

    f.setArguments(args);

    return f;

  }

使用

Myfragment.newInstance(1);

方法二

 public MyFragment newInstance(int index) {

    Bundle args = new Bundle(1);

    args.putInt("index", index);

    setArguments(args);

    return this;
  }

使用

new Myfragment().newInstance(1);

在上面的代码片段中,哪一种更合适,更可取,请指出原因?

现在正在做这个..

 List<Fragment> fragments = new ArrayList<>();
            fragments.add(new MyFragment().newInstance(defaultId));
            int i = 1;
            for (Categories categories : mCategories) {
                String id = categories.getCategory_id();
                String name = categories.getCategory_name();
//                String slno = categories.getSlno();
                fragments.add(new MyFragment().newInstance(defaultId));
                Titles[i] = name;
                i++;
            }

这有什么问题吗?

方法 1 优于方法 2。

那是因为在方法 1 中,您实际上创建了一个 MyFragment 对象。在方法 2 中,您首先创建一个 MyFragment 对象,然后使用 newInstance(...) 对其进行初始化。如果您想使用方法 2,我建议分两行进行:

MyFragment frag = new MyFragment();
frag.initialize(1);

使用初始化方法:

public void initialize(int index) {
    Bundle args = new Bundle(1);
    args.putInt("index", index);
    setArguments(args);
}

继续Method 1。始终尝试使用 Static Factory Methods 而不是 Constructors。为什么需要使用它可以在 Joshua Bloch 的名著 Effective Java 中找到:Item1 - Static Factory Method。

您也可以参考:Effective Java By Joshua Bloch: Item1 - Static Factory Method