为什么我必须在 Android 中将 Bundle 传递给 Fragment
Why I have to pass Bundle to Fragment in Android
我们在给fragment传递参数时,通常使用下面的样式
public static MyFragment newInstance() {
MyFragment fragment = new MyFragment();
String myVariable = "My variable string";
Bundle bundle = new Bundle();
bundle.putString("myVariable", myVariable);
fragment.setArguments(bundle);
return fragment;
}
当我们使用 getter setter 方法时会发生什么:
private String myVariable;
public String getMyVariable() {
return myVariable;
}
public void setMyVariable(String myVariable) {
this.myVariable = myVariable;
}
public static MyFragment newInstance() {
MyFragment fragment = new MyFragment();
String passVariable = "My variable string";
fragment.setMyVariable(passVariable);
return fragment;
}
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String passVariable = getMyVariable();
}
我用第二种方式测试时,没有出现问题。那为什么要用第一种方式呢?
我也看到了post“Why use bundle to pass data to fragment?”。他们说 "it's easier for the system to restore its values when the fragment is re-instantiated"
但我测试了如果片段从堆栈中弹出,变量仍然存在。
如果框架需要重新创建您的片段,您使用第二个 setter 方法设置的数据将丢失。
参数包持续到重新创建的片段。
我们在给fragment传递参数时,通常使用下面的样式
public static MyFragment newInstance() {
MyFragment fragment = new MyFragment();
String myVariable = "My variable string";
Bundle bundle = new Bundle();
bundle.putString("myVariable", myVariable);
fragment.setArguments(bundle);
return fragment;
}
当我们使用 getter setter 方法时会发生什么:
private String myVariable;
public String getMyVariable() {
return myVariable;
}
public void setMyVariable(String myVariable) {
this.myVariable = myVariable;
}
public static MyFragment newInstance() {
MyFragment fragment = new MyFragment();
String passVariable = "My variable string";
fragment.setMyVariable(passVariable);
return fragment;
}
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String passVariable = getMyVariable();
}
我用第二种方式测试时,没有出现问题。那为什么要用第一种方式呢?
我也看到了post“Why use bundle to pass data to fragment?”。他们说 "it's easier for the system to restore its values when the fragment is re-instantiated" 但我测试了如果片段从堆栈中弹出,变量仍然存在。
如果框架需要重新创建您的片段,您使用第二个 setter 方法设置的数据将丢失。
参数包持续到重新创建的片段。