3 回答

TA貢獻1827條經(jīng)驗 獲得超4個贊
您每次在活動中打開屏幕時都在創(chuàng)建一個新的片段,onCreate();但是您也要使用來維護舊的片段super.onCreate(savedInstanceState);。因此,也許設置標簽并找到片段(如果存在),或者將空束傳遞給super。
這花了我一些時間來學習,當您使用諸如viewpager之類的東西時,它確實可以說是一個爛攤子。
我建議您多花一些時間閱讀有關片段的內(nèi)容,因為涉及到了這個確切的主題。
這是一個如何在規(guī)則的方向變化中處理碎片的示例:
活動內(nèi)容:
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
TestFragment test = new TestFragment();
test.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, test, "your_fragment_tag").commit();
} else {
TestFragment test = (TestFragment) getSupportFragmentManager().findFragmentByTag("your_fragment_tag");
}
}
}
片段:
public class TestFragment extends Fragment {
public static final String KEY_ITEM = "unique_key";
public static final String KEY_INDEX = "index_key";
private String mTime;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_layout, container, false);
if (savedInstanceState != null) {
// Restore last state
mTime = savedInstanceState.getString("time_key");
} else {
mTime = "" + Calendar.getInstance().getTimeInMillis();
}
TextView title = (TextView) view.findViewById(R.id.fragment_test);
title.setText(mTime);
return view;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("time_key", mTime);
}
}

TA貢獻1828條經(jīng)驗 獲得超6個贊
可以在android準則中找到有關如何在方向變化和活動娛樂之間保留數(shù)據(jù)的良好準則。
摘要:
使您的片段可保留:
setRetainInstance(true);
僅在必要時創(chuàng)建新片段(或至少從中獲取數(shù)據(jù))
dataFragment = (DataFragment) fm.findFragmentByTag("data");
// create the fragment and data the first time
if (dataFragment == null) {
- 3 回答
- 0 關注
- 492 瀏覽
添加回答
舉報