You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Xamarin.Android使用XML切换页面时如何复用同一左侧汉堡菜单

问题根因

你在SecondActivity里照搬MainActivity的初始化代码,调用了SetContentView(Resource.Layout.activity_main),相当于重复加载了包含toolbar、DrawerLayout的根布局,才会触发toolbar重复加载的报错。另外多Activity复用全局汉堡菜单的方案本身就不合理,安卓原生带全局侧边栏的应用均采用单Activity+多Fragment的方案实现内容切换,不需要创建多个Activity。

正确实现步骤(仅用安卓XML布局,不涉及XAML)
  • 保留MainActivity作为唯一的宿主Activity,原有初始化toolbar、侧边栏、菜单监听的代码无需改动
  • 删除你新建的SecondActivity.cs,second_content_page.xml直接作为Fragment的布局使用
  • 新建SecondContentFragment类,关联对应的布局:
public class SecondContentFragment : AndroidX.Fragment.App.Fragment
{
    public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
    {
        return inflater.Inflate(Resource.Layout.second_content_page, container, false);
    }
}
  • 调整activity_main.xml的结构,新增id为content_container的FrameLayout作为内容承载容器,替换原来直接嵌入content_page的部分
  • 在MainActivity的菜单选中监听方法里处理内容切换逻辑:
public bool OnNavigationItemSelected(IMenuItem item)
{
    AndroidX.Fragment.App.Fragment targetFragment = null;
    switch (item.ItemId)
    {
        case Resource.Id.nav_home:
            // 首页对应你原来的content_page,自己封装HomeContentFragment即可
            targetFragment = new HomeContentFragment();
            break;
        case Resource.Id.nav_second_page:
            // 第二个页面对应你新增的布局
            targetFragment = new SecondContentFragment();
            break;
    }
    if (targetFragment != null)
    {
        SupportFragmentManager.BeginTransaction()
            .Replace(Resource.Id.content_container, targetFragment)
            .Commit();
    }
    // 点击后关闭侧边栏
    FindViewById<DrawerLayout>(Resource.Id.drawer_layout).CloseDrawer(GravityCompat.Start);
    return true;
}
多Activity实现备选方案

如果坚持要用多Activity实现,避免重复报错的方法如下:

  • 把toolbar、DrawerLayout、NavigationView抽成独立的公共布局文件,用<include>标签引入到每个Activity的布局中,不要直接复用activity_main.xml
  • 每个Activity单独实现菜单选中监听,处理跳转逻辑,跳转时注意清理Activity栈避免冗余,该方案代码重复度高,优先推荐Fragment方案。

内容的提问来源于stack exchange,提问作者Exception

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 06:54:03