2013-08-29 36 views
9

我的應用程序的結構是這樣的:確定堆棧中的片段空狀態的Android

SplashActivity -> MainActivity -> (switching between many fragments) 

我期待什麼:從主要活動結束應用程序時,片段回棧計數爲零。這裏是我的嘗試:

在SplashAcitivty

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    if (getIntent().getBooleanExtra("exit", false)) { 
     finish(); 
    } 
    } 

在MainActivity

@Override 
public void onBackPressed() { 
    // I need to implement this method 
    if(backstackCount() == 0){ 
    Intent intent = new Intent(this, SplashActivity.class); 
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
    intent.putExtra(SplashActivity.EXIT_KEY, true); 
    startActivity(intent); 
    }else{ 
    super.onBackPressed(); 
    } 
} 

那麼,請告訴我,我怎麼能確定返回堆疊它的時候是空的?因爲我使用了SlideMenu庫,所以我的所有片段都會多次切換,並且在切換時將它們添加到背堆棧中。看起來像這樣:

getSupportFragmentManager() 
    .beginTransaction() 
    .replace(R.id.content_frame, fragment) 
    .addToBackStack(null) 
    .commit(); 
+6

你可以使用'getBackStackEntryCount' – dreamcoder

+0

@dreamcoder謝謝,它的工作。我不相信我不知道這個。你能回答我的問題,然後我可以接受嗎? – R4j

回答

24

這是我的代碼。它適用於我:

@Override 
public void onBackPressed() { 

    int backStackEntryCount = getSupportFragmentManager().getBackStackEntryCount(); 
    if (backStackEntryCount == 0) { 
     goBack(); // write your code to switch between fragments. 
    } else { 
     super.onBackPressed(); 
    } 
} 
+1

錯過了一個厚臉皮的'}'在那裏。 –