簡體   English   中英

Android popBackStack()無法還原先前的片段

[英]Android popBackStack() not restoring previous fragment

我有兩個片段MapScreenFragment和SessionSetUpFragment,它們與我的活動MapsActivity一起進出。 我總是先去MapScreenFragment,然后在MapScreenFragment上有一個按鈕,該按鈕會回調MapsActivity並將當前片段替換為SessionSetUpFragment。 因此,片段管理器堆棧應具有SessionSetUpFragment和MapScreenFragment。 當我在SessionSetUpFragment上按下android后退按鈕時,它顯示空白屏幕,並且從未調用MapScreenFragment的onCreateView()或onResume()。 另一個android后退按鈕調用將關閉該應用程序。 如何使MapScreenFragment恢復?

編輯:如果我改變

getFragmentManager().popBackStack("sessFrag", FragmentManager.POP_BACK_STACK_INCLUSIVE);

getFragmentManager().popBackStack();

問題仍然存在,但在應用關閉之前,我還有一個空白的后屏幕

在此處輸入圖片說明在此處輸入圖片說明

MapScreenFramget.java:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    // Inflate the layout for this fragment
    View view = inflater.inflate(R.layout.fragment_map, container, false);

    Log.d(TAG,"onCreateView"); //Never gets called
}

@Override
public void onResume() {
    Log.d(TAG,"onResume"); //Never gets called
    super.onResume();
}

MapsActivity.java:

 @Override
 public void logIn(){
     MapScreenFragment mapFrag = new MapScreenFragment();
     getFragmentManager().beginTransaction().replace(R.id.mainContainer, mapFrag).addToBackStack("mapFrag").commit();
 }

 @Override
 public void sessionSetUp(){
     SessionSetUpFragment sessFrag = new SessionSetUpFragment();
     getFragmentManager().beginTransaction().replace(R.id.mainContainer, sessFrag).addToBackStack("sessFrag").commit();
 }

@Override
public void onBackPressed() {
    if(fm.getBackStackEntryCount() > 0) {
        Log.i(TAG, fm.getBackStackEntryAt(fm.getBackStackEntryCount() - 1) + " Popped! " + (fm.getBackStackEntryCount() - 1) + " stacks left!");

        getFragmentManager().popBackStack("sessFrag", FragmentManager.POP_BACK_STACK_INCLUSIVE);
    }else {
        super.onBackPressed();
    }
}

由於MapScreenFragment是您的第一個片段,因此您可能希望嘗試在login()方法中調用add()而不是replace() 並且不要將其添加到堆棧中。 MapScreenFragment添加到后堆棧會導致您看到空白空間。

接下來,您的sessionSetUp()方法看起來不錯。 由於已經將SessionSetUpFragment添加到backStack中,因此無需覆蓋onBackPressed() 這一直對我有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM