3 回答

TA貢獻(xiàn)1827條經(jīng)驗(yàn) 獲得超4個(gè)贊
您每次在活動(dòng)中打開屏幕時(shí)都在創(chuàng)建一個(gè)新的片段,onCreate();但是您也要使用來維護(hù)舊的片段super.onCreate(savedInstanceState);。因此,也許設(shè)置標(biāo)簽并找到片段(如果存在),或者將空束傳遞給super。
這花了我一些時(shí)間來學(xué)習(xí),當(dāng)您使用諸如viewpager之類的東西時(shí),它確實(shí)可以說是一個(gè)爛攤子。
我建議您多花一些時(shí)間閱讀有關(guān)片段的內(nèi)容,因?yàn)樯婕暗搅诉@個(gè)確切的主題。
這是一個(gè)如何在規(guī)則的方向變化中處理碎片的示例:
活動(dòng)內(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貢獻(xiàn)1828條經(jīng)驗(yàn) 獲得超6個(gè)贊
可以在android準(zhǔn)則中找到有關(guān)如何在方向變化和活動(dòng)娛樂之間保留數(shù)據(jù)的良好準(zhǔn)則。
摘要:
使您的片段可保留:
setRetainInstance(true);
僅在必要時(shí)創(chuàng)建新片段(或至少從中獲取數(shù)據(jù))
dataFragment = (DataFragment) fm.findFragmentByTag("data");
// create the fragment and data the first time
if (dataFragment == null) {
- 3 回答
- 0 關(guān)注
- 505 瀏覽
添加回答
舉報(bào)