2015-10-31 26 views
1

我已经创建了一个家庭活动,其中包括一个导航抽屉onclick与片段。我已经包含fragmentTransaction.addToBackStack(null).commit();与片段事务代码。但它不会回到上一页,而是关闭应用程序。Android片段addToBackStack不能使用导航抽屉

在我MainActivity

@SuppressWarnings("StatementWithEmptyBody") 
@Override 
public boolean onNavigationItemSelected(MenuItem item) { 
    FragmentManager fragmentManager = getSupportFragmentManager(); 
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
    // Handle navigation view item clicks here. 
    int id = item.getItemId(); 
    RelativeLayout mainLayout=(RelativeLayout)findViewById(R.id.mainlayout); 

    if (id == R.id.nav_project) { 
     ProjectFragment fragment = new ProjectFragment(); 
     mainLayout.removeAllViews(); 
     fragmentTransaction.replace(R.id.mainlayout, fragment); 
     fragmentTransaction.addToBackStack(null).commit(); 

    } 

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    drawer.closeDrawer(GravityCompat.START); 
    return true; 
} 
@Override 
    public void onBackPressed() { 
     DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
     if (drawer.isDrawerOpen(GravityCompat.START)) { 
      drawer.closeDrawer(GravityCompat.START); 
     } else { 
      super.onBackPressed(); 
     } 
    } 

我的默认Fragment

public class ProjectFragment extends Fragment { 

     @Nullable 
     @Override 
     public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
      View v = inflater.inflate(R.layout.fragment_project, container, false); 

      return v; 
     } 



} 

谁能帮我找出这个问题。

+0

你是什么意思“但它没有反应。”?当您点击后退键时,应用程序是否会退出到首页? –

+0

它不会回到上一页,而是关闭应用程序。 –

+1

感谢Rubin为您的文本修改。也许你会得到更多的关注,你有我的,嘿嘿。 –

回答

1

感谢您的回应,它有帮助。基本上你需要添加一个片段到堆栈

而不是使用replace(),使用fragmentTransactionadd方法。这会给你想要的效果。

简单样品:fragmentTransaction.add(R.id.mainlayout, fragment);

+1

非常感谢你先生/但它只适用于一个过渡。 –

+0

@RubinNellikunnathu,你在另一个片段转换上崩溃了吗?我以为你是。 –

+0

是的,我崩溃了。 –