无法将TextView置于Toolbar下方,求Android布局修改方案
解决TextView无法显示在Toolbar下方的问题
嘿,作为Android新手碰到这种布局定位问题太正常啦!你提到的app:layout_behavior="@string/appbar_scrolling_view_behavior"其实是CoordinatorLayout专属的布局行为属性,但你当前的根布局是RelativeLayout,这就是为啥这个属性对你没用的核心原因~下面给你两种可行的解决方案,按需选择:
方案一:改用标准的CoordinatorLayout布局体系(推荐)
这是Android官方推荐的搭配Toolbar的布局结构,后续如果要实现滚动联动(比如Toolbar隐藏/显示)也会更方便。完整的布局示例如下:
<?xml version="1.0" encoding="utf-8"?> <androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- AppBar区域:包含Toolbar --> <com.google.android.material.appbar.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/Theme.App.AppBarOverlay"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/Theme.App.PopupOverlay"/> </com.google.android.material.appbar.AppBarLayout> <!-- 你的TextView:现在加上behavior就能自动定位到Toolbar下方 --> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="我现在在Toolbar下面啦!" app:layout_behavior="@string/appbar_scrolling_view_behavior"/> </androidx.coordinatorlayout.widget.CoordinatorLayout>
说明:记得确保你的项目已经引入了Material Design组件依赖(AndroidX版本),这个behavior才能生效。
方案二:继续使用RelativeLayout(适合简单场景)
如果你不想换根布局,直接在RelativeLayout里通过相对定位属性就能把TextView放在Toolbar下方,步骤如下:
- 给你的Toolbar设置一个唯一ID,比如
android:id="@+id/toolbar" - 给TextView添加
android:layout_below="@id/toolbar"属性,让它跟在Toolbar下方
示例代码片段:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary"/> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="我在Toolbar下面啦!" android:layout_below="@id/toolbar"/> </RelativeLayout>
小提醒:如果还是出现重叠,检查一下Toolbar的layout_height是不是设置正确(用?attr/actionBarSize是最稳妥的),同时确保TextView没有设置layout_alignParentTop="true"这类会让它跑到顶部的属性哦~
内容的提问来源于stack exchange,提问作者Sidharth K.Burnwal
相关产品推荐
相关产品推荐

