2016-09-03 42 views
1

當我單擊後退按鈕時,我想要移回到之前的片段。我正在做的是不工作。如何在Android中返回前一個片段

的片段替換代碼:

Fragment fragment=new MyFragment(); 
FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); 
FragmentTransaction fragmentTransaction = fragmentManager 
    .beginTransaction(); 
fragmentTransaction.setCustomAnimations(R.anim.slide_in,R.anim.slide_out); 
fragmentTransaction.replace(R.id.container_body, fragment); 
fragmentTransaction.commit(); 

的後退按鈕的捕撈命中代碼:

@Override 
public void onResume() { 
    super.onResume(); 
    getActivity().invalidateOptionsMenu(); 
    getView().setFocusableInTouchMode(true); 
    getView().requestFocus(); 
    getView().setOnKeyListener(new View.OnKeyListener() { 
     @Override 
     public boolean onKey(View v, int keyCode, KeyEvent event) { 
      if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) { 
       getActivity().finish(); 
       getActivity().overridePendingTransition(R.anim.slide_enter, R.anim.slide_exit); 
       return true; 
      } 
      return false; 
     } 
    }); 

我也曾嘗試

getActivity().getSupportFragmentManager().popBackStack(); 
+0

fragmentTransaction.addtobackstack(fragment.getClass()。getSimpleName()); –

+0

我已經執行但仍然沒有工作 – Shivangi

+0

看到這個鏈接http://stackoverflow.com/questions/18305945/how-to-resume-fragment-from-backstack-if-exists –

回答

0

改變這樣這個墊子幫助

Fragment fragment=new MyFragment(); 
       FragmentManager fragmentManager = getActivity().getSupportFragmentManager(); 
       FragmentTransaction fragmentTransaction = fragmentManager 
         .beginTransaction(); 
       fragmentTransaction.setCustomAnimations(R.anim.slide_in,R.anim.slide_out); 
       fragmentTransaction.replace(R.id.container_body, fragment).addToBackStack(null); 
       fragmentTransaction.commit(); 

讓我知道是否有任何錯誤

+0

沒有錯誤,但後退按鈕停止工作。 – Shivangi

+0

.addToBackStack(null);加入你要聽後退按鈕CONTROLE – Manish

+0

沒什麼每個片段happend – Shivangi

0

你可以像下面這樣做。

DetailsFragment detailsFragment = new DetailsFragment(); 
      Bundle bundle = new Bundle(); 
      bundle.putString("ID", Id); 
        detailsFragment.setArguments(bundle); 

      FragmentTransaction transaction = getFragmentManager().beginTransaction(); 
      transaction.add(R.id.detail_container, detailsFragment); 
      transaction.addToBackStack(this.getClass().getSimpleName()); 
      transaction.hide(DetailsFragment.this); 
      transaction.commit(); 
相關問題