[英]Android fragment addToBackStack not working with Navigation drawer
I had Created a Home activity which includes a Navigation Drawer onclick with fragment. 我创建了一个Home活动,其中包括带有片段的导航抽屉onclick。 I had included
fragmentTransaction.addToBackStack(null).commit();
我已经包含
fragmentTransaction.addToBackStack(null).commit();
with the fragment transaction code. 与片段交易代码。 But it doesn't go back to previous page,instead it is closing the app.
但它不会返回上一页,而是正在关闭该应用程序。
In My MainActivity
在我的
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();
}
}
My Default Fragment
我的默认
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;
}
}
Can anyone help me to figure out this problem. 谁能帮我解决这个问题。
Thanks for your response, it helps. 感谢您的回复,它会有所帮助。 Basically you need to add a fragment to the stack .
基本上,您需要向堆栈中添加一个片段 。
Instead of using replace
(), use the add
method of fragmentTransaction
. 代替使用
replace
(),使用fragmentTransaction
的add
方法。 This will give you the desired effect. 这将给您想要的效果。
Easy sample: fragmentTransaction.add(R.id.mainlayout, fragment);
简单示例:
fragmentTransaction.add(R.id.mainlayout, fragment);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.