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

Android布局添加ActionBar遇多根标签错误求助

解决Android布局的Multiple Root Tag错误

嘿,这个问题很常见——Android的布局XML文件必须只能有一个根视图元素,你现在的代码里直接把Toolbar和ScrollView放在最外层,相当于有两个根标签,系统自然就报错啦。

修复思路

找一个合适的容器视图(比如LinearLayout或者ConstraintLayout)把所有元素包起来,让整个布局只有一个根节点。这里用LinearLayout比较简单,因为你的布局是垂直排列的(Toolbar在上,滚动区域在下)。

另外还要注意两个小问题:

  • 不要重复声明xmlns:android,只需要在根元素里写一次就行
  • 你提供的代码里有未闭合的标签(比如TableLayout、ScrollView),也要补上闭合标签

修正后的完整代码

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!-- Toolbar作为顶部导航栏 -->
    <android.support.v7.widget.Toolbar 
        android:id="@+id/my_toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        android:elevation="4dp"
        android:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

    <!-- 滚动区域 -->
    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"> <!-- 让ScrollView填充剩余空间 -->

        <TableLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:stretchColumns="1"
            android:layout_margin="4dp">

            <CheckBox
                android:id="@+id/c1"
                android:layout_width="match_parent"
                android:layout_height="70dp"
                android:textSize="20sp"
                android:text="@string/c1"
                android:layout_margin="2dp"
                android:onClick="onCheckboxClicked"
                android:background="#00FF00"/>
        </TableLayout> <!-- 闭合TableLayout -->
    </ScrollView> <!-- 闭合ScrollView -->
</LinearLayout> <!-- 闭合根LinearLayout -->

额外说明

  • 给ScrollView加上android:layout_weight="1"是为了让它在Toolbar占据固定高度后,自动填充剩余的屏幕空间
  • 如果你的项目已经迁移到AndroidX,记得把android.support.v7.widget.Toolbar替换成androidx.appcompat.widget.Toolbar,避免兼容性问题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 10:17:16