2015-04-02 72 views
0

我是Android和片段的新手,所以我認爲我錯過了一些重要的東西。 我有一個主要活動和2個片段,第二個替換第一個替換活動。我提交了一個替換事務,不會因爲某種原因而忘記調用addToBackStack(null),每當我按下後退按鈕時(從第二個片段開始),應用程序就會返回桌面屏幕,並且應用程序通過最近的應用程序屏幕可用,始終顯示主要活動。返回按鈕在片段中返回到主屏幕

這是怎麼發生的?

MainActivity.java

... 
     else if (id == R.id.action_settings) { 

     FragmentTransaction fragmentTransaction = getFragmentManager() 
       .beginTransaction(); 
     fragmentTransaction.setCustomAnimations(R.anim.enter, R.anim.exit); 
     fragmentTransaction.replace(R.id.MainLayout, 
       new SettingsFragment()); 
     fragmentTransaction.addToBackStack(null); 
     fragmentTransaction.commit(); 
     return true; 
    } 

SettingsFragment.java

public View onCreateView(LayoutInflater inflater, ViewGroup container, 
         Bundle savedInstanceState){ 
... 
     @Override 
     public void onClick(View v) { 

      FragmentTransaction fragmentTransaction = getFragmentManager() 
        .beginTransaction(); 
      fragmentTransaction.replace(R.id.MainLayout, 
        new SelectBackgroundFragment()); 
      fragmentTransaction.addToBackStack(null); 
      fragmentTransaction.commit(); 

     } 
    }); 
+0

你要移到前面的片段? – Fahim 2015-04-02 01:16:43

回答

0

你需要重寫onBackPressed您的活動:

@Override 
    public void onBackPressed() { 
     if (getFragmentManager().getBackStackEntryCount() > 0) { 
      getFragmentManager().popBackStackImmediate(); 
     } else { 
      super.onBackPressed(); 
     } 
    } 
+0

非常感謝! – 2015-04-02 09:30:58