gpt4 book ai didi

Android fragment addToBackStack不适用于抽屉导航

转载 作者:行者123 更新时间:2023-11-30 01:47:57 24 4
gpt4 key购买 nike

我创建了一个 Home Activity ,其中包含带有 fragment 的 Navigation Drawer onclick。我已将 fragmentTransaction.addToBackStack(null).commit(); 包含在 fragment 事务代码中。但是它不会返回到上一页,而是关闭应用程序。

在我的 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;
}



}

谁能帮我解决这个问题。

最佳答案

感谢您的回复,很有帮助。基本上,您需要向堆栈添加 fragment

不使用replace(),而是使用fragmentTransactionadd 方法。这将为您带来预期的效果。

简单示例:fragmentTransaction.add(R.id.mainlayout, fragment);

关于Android fragment addToBackStack不适用于抽屉导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33448555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com