我是新來的android和我面臨以下問題。我正在爲Android 2和3開發,這就是我使用片段的原因。然而,爲了使應用程序在Android 2設備上工作,我導入了android.support.v4.app.ListFragment。當屏幕的方向改變時,我需要在ListFragment中保持選擇。我重寫onSaveInstanceState()
方法,並將一個int放入該包中。當屏幕旋轉時,將調用此方法,並將int添加到包中。但是,當調用onActivityCreated()
時,其捆綁包爲空。我遵循Android網站上提供的示例:http://developer.android.com/reference/android/app/Fragment.html,但如上所述 - 在調用onSaveInstanceState()
之後,onActivityCreated()
中的包仍爲空。Android的ListFragment不保存在onSaveInstanceState()中的包/不檢索包onActivityCreated()
下面的代碼:
import android.support.v4.app.ListFragment;
public class VisitsHomeFragment extends ListFragment {
private int selectedPosition = -1;
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
if (savedInstanceState.containsKey("SELECTED_POSITION")) {
selectedPosition = savedInstanceState.getInt("SELECTED_POSITION");
}
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("SELECTED_POSITION", selectedPosition);
}
}
我很感激這個問題的任何幫助。
onRestoreInstanceState()不可用於片段。 – Maria
我唯一的建議是調試compat的來源,看看你是否能掌握正在發生的事情。 – PJL
我玩過示例項目(HoneycombGallery),向它添加了兼容庫,並且一切正常......在我的應用程序中 - 它沒有。對我來說,臨時解決方案是在Manifest中添加'android:configChanges ='orientation'',但它並不能解決丟失的包的奧祕(實際上是想寫一本名爲「失落包的奧祕」 ;-))。 – Maria