简体   繁体   English

实例化片段的最佳方法?

[英]Best way to instantiate a fragment?

Method 1方法一

public static MyFragment newInstance(int index) {

    MyFragment f = new MyFragment();

    Bundle args = new Bundle(1);

    args.putInt("index", index);

    f.setArguments(args);

    return f;

  }

Usge使用

Myfragment.newInstance(1);

Method 2方法二

 public MyFragment newInstance(int index) {

    Bundle args = new Bundle(1);

    args.putInt("index", index);

    setArguments(args);

    return this;
  }

Usge使用

new Myfragment().newInstance(1);

In the above snippets which one is more appropriate and preferable way and please point out why ?在上面的片段中,哪一种更合适和更可取,请指出为什么?

And now am doing this..现在正在做这个..

 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++;
            }

Anything wrong with this ?这有什么问题吗?

Method 1 would be preferred over Method 2.方法 1 优于方法 2。

That's because in Method 1 you really create a MyFragment object.那是因为在方法 1 中,您确实创建了一个MyFragment对象。 In Method 2 you first create a MyFragment object and then you initialize it with newInstance(...) .在方法 2 中,您首先创建一个MyFragment对象,然后使用newInstance(...)对其进行初始化。 If you want to use method 2 i'd suggest to do it in 2 lines:如果您想使用方法 2,我建议分两行进行:

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

with the initialize method:使用初始化方法:

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

Go ahead with Method 1 .继续Method 1 Always try to use Static Factory Methods over Constructors .始终尝试在Constructors上使用Static Factory Methods Why you need to use this could be found out in the famous book Effective Java By Joshua Bloch: Item1 - Static Factory Method.为什么需要使用它可以在 Joshua Bloch 的著名书籍Effective Java找到:Item1 - Static Factory Method。

Also you could refer: Effective Java By Joshua Bloch: Item1 - Static Factory Method您也可以参考: Joshua Bloch 的 Effective Java:Item1 - 静态工厂方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM