我有一个Fragment将一个ArrayList,newStyles发送到它的FragmentActivity,mStyles,然后使用addAll将其清除。我使用.size()来检查数组并注意在调用addAll后清除源newStyles:
以下将在调用addAll之前为newStyles提供正确的大小,但在清除之后将为0大小:
public void setStyles(ArrayList<String[][]> newStyles) {
Log.d(TAG, "setStyles: mStyles.size() = " + mStyles.size());
Log.d(TAG, "setStyles: newStyles.size() = " + newStyles.size());
mStyles.clear();
mStyles.addAll(newStyles);
Log.d(TAG, "setStyles: mStyles.size() = " + mStyles.size());
Log.d(TAG, "setStyles: newStyles.size() = " + newStyles.size());
}
最终发生的事情是ArrayLists最终的大小为0。
更新
我通过使用:
解决了它mStyles = new ArrayList<String[][]>(newStyles);
但我仍然想知道发生了什么,所以这里是必要的信息
以下是在活动中:
ArrayList<String[][]> mStyles;
protected void onCreate(Bundle savedInstanceState) {
...
mStyles = new ArrayList<String[][]>();
....
}
// Called by StylesFragment to preLoad styles from the file when
// the Fragment is viewed
public ArrayList<String[][]> getStylesFromFile() {
mStyles.clear();
mStyles.addAll(mTotalsFragment.getStyles());
return mStyles;
}
// Called by StylesFragment when changes are made to styles
public void setStyles(ArrayList<String[][]> newStyles) {
Log.d(TAG, "setStyles: mStyles.size() = " + mStyles.size());
Log.d(TAG, "setStyles: newStyles.size() = " + newStyles.size());
mStyles.clear();
mStyles.addAll(newStyles);
Log.d(TAG, "setStyles: mStyles.size() = " + mStyles.size());
Log.d(TAG, "setStyles: newStyles.size() = " + newStyles.size());
}
以下是Totals Fragment:
ArrayList<String[][]> mStyles;
public void onActivityCreated(Bundle savedInstanceState) {
...
mStyles = new ArrayList<String[][]>();
...
}
public void loadEstimate() {
...
// Do loop here to pull data from a file
mStyle = ...
...
}
// Called by StylesFragment via Activity
// to get Loaded data from file
public ArrayList<String[][]> getStyles() {
return mStyles;
}
public void saveEstimate() {
...
// Get the styles that should be in Activity
mStyles = ((PagerActivityFragment)getActivity()).getStyles();
// Save the file with the new information
...
}
以下是在StylesFragment中:
ArrayList<String[][]> mStyles;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
mStyles = new ArrayList<String[][]>();
...
}
public void onResume() {
...
// Pull the styles loaded from the file through Activity
mStyles = ((PagerActivityFragment)getActivity()).getStylesFromFile();
...
}
public modifyStyle(stylePos) {
...
// Do some stuff here to modify a specific style (String[][]) within the ArryaList
// Now send changes back to Activity so TotalsFragment can pull it
// even if this Fragment is not available when file is to be saved
((PagerActivityFragment)getActivity()).setStyles(mStyles);
}
答案 0 :(得分:0)
return mStyles
中的getStylesFromFile()
中的Activity
正在返回对mStyles
列表的引用,这就是为什么两者都指向相同的列表。