Android Fragment 实例化:newInstance()

Mer*_*aya 1 java android android-fragments

我读了很多文章和 StackOverflow 答案,但仍然无法理解为什么我们需要工厂方法来创建 Fragment 的实例。

以下 Fragment 类都可以正常工作。

具有两个构造函数的片段:

public class CtorFragment extends Fragment {
    private static final String KEY = "the_key";

    public CtorFragment() {
        // Android calls the default constructor so default constructor must be explicitly defined.
        // As we have another constructor, Android won't create a default constructor for us.
    }

    public CtorFragment(String s) {
        // Set the arguments.
        Bundle bundle = new Bundle();
        bundle.putString(KEY, s);

        setArguments(bundle);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View fragment = inflater.inflate(R.layout.fragment_my, container, false);
        TextView textView = (TextView) fragment.findViewById(R.id.textView);

        // Use getArguments() to get the String argument set by the constructor with parameter.
        textView.setText(getArguments().getString(KEY));
        return fragment;
    }
}
Run Code Online (Sandbox Code Playgroud)

具有静态工厂方法的片段:

public class StaticFragment extends Fragment {
    private static final String KEY = "the_key";

    public static StaticFragment newInstance(String s) {
        StaticFragment fragment = new StaticFragment();
        // Set the arguments.
        Bundle bundle = new Bundle();
        bundle.putString(KEY, s);

        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View fragment = inflater.inflate(R.layout.fragment_my, container, false);
        TextView textView = (TextView) fragment.findViewById(R.id.textView);

        // Use getArguments() to get the String argument set by the constructor with parameter.
        textView.setText(getArguments().getString(KEY));
        return fragment;
    }
}
Run Code Online (Sandbox Code Playgroud)

您能否解释一下为什么每个人(包括Google)都“强烈推荐”使用静态工厂方法的方法?我和其他非 Android 背景的人是否缺少一些重要的东西?

是不是我们必须定义两个方法(构造函数)而不是一个(静态工厂方法),这会引起所有的麻烦?

Com*_*are 6

仍然不明白为什么我们需要一个工厂方法来创建 Fragment 的实例

“需要”是一个很强烈的词。您并不“需要”工厂方法。你确实需要:

  • 一个公共的零参数构造函数,最好是空的;和

  • 设置片段的有组织的方法,以在配置更改后仍然存在的方式

您能否解释一下为什么每个人(包括Google)都“强烈推荐”使用静态工厂方法的方法?

如果 Java 类上没有显式构造函数,则会自动获得一个空的公共零参数构造函数,这是框架创建片段所需的。

如果您创建一个带有参数的构造函数(例如,CtorFragment(String s)),那么您还必须记住创建公共零参数构造函数(CtorFragment())。你可能记得这样做。许多缺乏经验的程序员不会。

编写工厂方法可以实现与非零参数构造函数相同的目标,而不会破坏自动创建的零参数构造函数。

如果您是一位经验丰富的 Java 程序员,并且您不喜欢工厂方法,并且您可以阅读堆栈跟踪,否则请记住添加公共零参数构造函数,欢迎您创建其他构造函数并使用它们。