我会考虑让自定义对象保持每个片段的填充数据。喜欢的东西:
public class FillerData implements Parcelable {
private String page0$data0;
private String page0$data1;
private String page0$data2;
// getters and setters if you wish
// implement Parcelable interface as this object will be managed by host activity
}
您将有一个唯一的对象由父活动管理和父活动将实现一个接口,用于暴露该对象:
public static interface FillerDataExposer {
public FillerData exposeFiller();
}
public class MyFragmentHostActivity extends FragmentActivity implements FillerDataExposer {
private static final String FILLER_KEY = "FILLER_KEY";
private FillerData myFillerData;
protected void onCreate(Bundle savedInstance) {
.......
if(savedInstance != null) {
myFillerData = (FillerData) savedInstance.getParcelable(FILLER_KEY);
} else {
myFillerData = new FillerData();
}
}
protected void onSaveInstanceState(Bundle savedInstance) {
super.onSaveInstanceState();
savedInstance.putExtra(FILLER_KEY, myFillerData);
}
public FillerData exposeFiller() {
return this.myFillerData;
}
}
现在,您的每一个片段都将有通过父级活动访问该集中式数据填充对象。
public abstract class AbstractFillerFragment extends Fragment {
protected FillerDataExposer dataExposer;
public void onAttach(Activity act) {
super.onAttach(act);
// make sure no ClassCastExceptions
this.dataExposer = (FillerDataExposer) act;
}
}
片段应该只记录填充可能看起来像数据:为了减少代码的重量,所有的碎片可能会从基片段类,它提供给FillerDataExposer
执行(实际上,父活动)的访问延长这样的:
public class Page1Fragment extends AbstractFillerFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = // inflate XML resource ...
yourEditText = (EditText) view.findViewById(...);
// other relevant code ....
}
public void onViewCreated(View view, Bundle savedInstanceState) {
yourEditText.setText(dataExposer.exposeFiller.setPageX$DataY());
// some code for EditText.addTextChangedListener(new TextWatcher() could look like:
yourEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
dataExposer.exposeFiller().setPage1$Data0(s.toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {}
});
}
}
当需要访问存储的所有数据片段看起来是这样的:
public class FinalFragment extends AbstractFillerFragment {
public void collectAllData() {
DataFiller allDataCollectedObject = dataExposer.exposeFiller();
// by calling get...() you should have access to collected data.
}
}
这只是一个草图,但你会得到的图片。这个想法是让活动中的单个对象在整个活动重新启动时进行管理,并使其可以通过接口进行访问,因此您可以将片段视为活动模式。
希望它是有道理的......
但我无法得到4个第一页的片段。他们甚至可能不存在。 – MTilsted