我创建了一个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;
}
}
任何人都可以帮我解决这个问题。
答案 0 :(得分:1)
感谢您的回复,这有帮助。基本上你需要将一个片段添加到堆栈。
不使用replace
(),而是使用add
的{{1}}方法。这将为您带来理想的效果。
简易样本:fragmentTransaction