2016-04-08 104 views
0

我有tried stackoverflow上的所有解決方案,但沒有幫助我。片段返回活動不工作

當我從默認片段回來,我想展現片段0,但在這裏的應用是密切

下面是MainActivity代碼

private void selectItem(int position) { 

    switch (position) { 
    case 0: 
     getSupportFragmentManager() 
       .beginTransaction().addToBackStack(PageSlidingTabStripFragment.TAG) 
       .replace(R.id.content, 
         PageSlidingTabStripFragment.newInstance(), 
         PageSlidingTabStripFragment.TAG).commit(); 
     break; 
    default: 

     SherlockFragment fragment = new PlanetFragment(); 
     Bundle args = new Bundle(); 
     args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position); 
     fragment.setArguments(args); 

     getSupportFragmentManager().beginTransaction() 
       .replace(R.id.content, fragment).commit(); 
     break; 
    } 

    mDrawerLayout.closeDrawer(mDrawerList); 
} 

第二塊碎片回活動

public void onBackPressed() { 
     FragmentManager fm = getFragmentManager(); 
     if(fm.getBackStackEntryCount() != 0) { 
      fm.popBackStack(); 
      fm.getBackStackEntryAt(0); 

     } else { 
      getActivity().onBackPressed(); 
     } 
    } 
+0

檢查活動如何使用接口與片段進行通信。 – Skynet

+0

可能的重複[如何從包含的片段控制活動的向上按鈕?](http://stackoverflow.com/questions/34025331/how-can-i-control-the-activitys-up-button-from-一個包含片段) –

回答

0

兄弟更改onBackPressed()中的條件:Like

Integer backStackSize = getFragmentManager().getBackStackEntryCount(); 

     if(backStackSize < 2){ 
      //new Logout_Dialog(MainActivity.this, MainActivity.this); 
//YOU CAN ASK USER WHETHER HE WANTS TO LOGOUT OR NOT HERE...... 
     } 
     else if(backStackSize >= 2){ 

      FragmentManager.BackStackEntry backEntry=getFragmentManager().getBackStackEntryAt(getFragmentManager().getBackStackEntryCount()-1); 


       fragmentManager.popBackStack(); 
     }//else if(backStackSize >= 2) closes here..... 
     else 
     { 
      //Else fragment shud be removed from Backstack.... 
      super.onBackPressed(); 
     }//fragment shud be removed from Backstack.. 
+0

得到onBackPressed()的方法未定義爲SherlockFragment類型 –

+0

@Nirav Ranpara:不,請在您的BaseActivity中進行擴展片段的操作。 片段沒有onBackPressed(),Activities有。 – Pawan

+0

在哪個文件中我應該寫上面的代碼 –