我一直在阅读有关使用工厂方法来获取自定义 Fragment
类的对象的信息。假设我有一个自定义 Fragment
类,如下所示:
public class CustomFragment extends Fragment {
..........
public static CustomFragment getInstance(String message) {
CustomFragment fragment = new CustomFragment();
Bundle bundle = new Bundle();
bundle.putString(MESSAGE, message);
fragment.setArguments(bundle);
return fragment;
}
..............
}
如果我有一个名为 MESSAGE 的类变量,并且我使用实例化对象上的 setter 设置其值,例如:
public class CustomFragment extends Fragment {
..........
private String MESSAGE;
private void setMessage(String msg) {
this.MESSAGE = msg;
}
public static CustomFragment getInstance(String message) {
CustomFragment fragment = new CustomFragment();
fragment.setMessage(message);
return fragment;
}
..............
}
以上两者中哪一个是首选,为什么?
最佳答案
Which of the above two is preferred
第一个。
why?
用户将旋转屏幕或以其他方式触发您的应用进行配置更改。默认情况下,您的前台 Activity 及其 fragment 将被销毁并重新创建。在第一个场景中,消息将成为保存的实例状态 Bundle
的一部分,并且不会丢失。在第二种情况下,消息将会丢失,除非您在某处添加额外的代码来专门保留它。
关于java - Fragment : Setting the class variables vs putting the Bundle as arguments in the Fragment 的工厂方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41332056/