我阅读了很多文章和 StackOverflow 的答案,但仍然不明白为什么我们需要工厂方法来创建 Fragment 的实例。
以下 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;
}
}
带有静态工厂方法的 fragment :
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;
}
}
你能解释一下为什么每个人(包括谷歌)都“强烈推荐”静态工厂方法吗?我和其他来自非 Android 背景的人是否遗漏了一些重要的东西?
是不是我们必须定义两个方法(构造函数)而不是一个(静态工厂方法)导致所有大惊小怪?
最佳答案
still cannot understand why we need a factory method to create an instance of a Fragment
“需要”是一个强词。您并不“需要”工厂方法。您确实需要:
一个公共(public)的零参数构造函数,最好是空的;和
一种有组织的方式来设置 fragment ,以一种在配置更改后仍然存在的方式
Can you please explain why everyone (including Google) "strongly recommends" the one with the static factory method?
如果您在 Java 类上没有显式构造函数,您会自动获得一个空的公共(public)零参数构造函数,这是框架创建 fragment 所需要的。
如果您创建一个带参数的构造函数(例如,CtorFragment(String s)
),那么您还必须记住创建公共(public)零参数构造函数(CtorFragment()
)。你可能会记得这样做。许多没有经验的程序员不会。
编写工厂方法可以实现与非零参数构造函数相同的目标,而不会破坏自动创建的零参数构造函数。
如果您是一位经验丰富的 Java 程序员,并且您不喜欢工厂方法,并且您可以阅读堆栈跟踪,否则请记住添加公共(public)零参数构造函数,欢迎您创建额外的构造函数并使用它们。
关于java - Android Fragment 实例化 : newInstance(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45839784/