我创建了一个Home活动,其中包括带有片段的导航抽屉onclick。我在片段事务代码中包含了fragmentTransaction.addToBackStack(null).commit();
。但它不会返回上一页,而是正在关闭该应用程序。
在我的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;
}
}
谁能帮我解决这个问题。
最佳答案
感谢您的回复,它会有所帮助。基本上,您需要向堆栈中添加一个片段。
代替使用replace
(),使用add
的fragmentTransaction
方法。这将给您想要的效果。
简易样本:fragmentTransaction.add(R.id.mainlayout, fragment);
关于android - Android fragment addToBackStack不适用于抽屉导航,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33448555/