构造函数与静态实例检索器

时间:2018-03-29 09:33:13

标签: java android constructor static

在学习android开发时,我遇到了以下代码部分:

/**
 * Static initializer for NetworkFragment that sets the URL of the host it will be downloading
 * from.
 */
public static NetworkFragment getInstance(FragmentManager fragmentManager, String url) {
    NetworkFragment networkFragment = new NetworkFragment();
    Bundle args = new Bundle();
    args.putString(URL_KEY, url);
    networkFragment.setArguments(args);
    fragmentManager.beginTransaction().add(networkFragment, TAG).commit();
    return networkFragment;
}

与使用类似构造函数相比,有什么好处:

public NetworkFragment(FragmentManager fragmentManager, String url) {
    Bundle args = new Bundle();
    args.putString(URL_KEY, url);
    networkFragment.setArguments(args);
    fragmentManager.beginTransaction().add(networkFragment, TAG).commit();
}

参考文献:Original Android Code

1 个答案:

答案 0 :(得分:0)

片段需要默认构造函数,要创建它的对象,它是必需的,所以要将参数传递给ur片段创建静态方法.......,这就是简单的原因