多くの記事とStackOverflowの回答を読みましたが、フラグメントのインスタンスを作成するためにファクトリメソッドが必要な理由を理解できません。Androidフラグメントのインスタンス化:newInstance()
次のフラグメントクラスはどちらも正常に動作します。
2つのコンストラクタを持つフラグメント:
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;
}
}
フラグメントstaticファクトリメソッドを持つ:
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;
}
}
(グーグルを含む)全員が、静的な工場で1を「強くお勧め」理由を説明していただけます方法?私と他の人がAndroid以外のバックグラウンドから逃れることが重要なことはありますか?
私たちはすべての騒ぎを引き起こすもの(静的なファクトリメソッド)ではなく、2つのメソッド(コンストラクタ)を定義する必要がありますか?
任意のファクトリメソッドと同様に、それは簡単 'それが簡単'新しいCtorFragment(「テキスト」)を書くことよりも、 '' StaticFragment.newInstance(「テキスト」)を書くことがいかに – Ramanlfc
@Ramanlfcクライアントにインスタンスを提供しますか? –
私はタイピングを意味しませんでした。つまり、良い抽象を提供しています。 – Ramanlfc