Toolbar遮挡内容视图,如何在XML中设置TextView避开状态栏与AppBar?
没问题!完全可以不用写代码,直接在XML里搞定这个需求,给你两个实用的方案:
方案1:用Material Design Behavior自动适配(强烈推荐)
如果你的项目用了CoordinatorLayout和AppBarLayout(这是现在Android应用做顶部栏的标准配置),只需要给你的TextView或者它的父容器加个Behavior属性,系统就会自动把TextView定位在AppBar的下方,状态栏和ActionBar的高度都会自动处理,根本不用自己算。
结合你的FrameLayout片段,示例代码是这样的:
<?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区域 --> <com.google.android.material.appbar.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content"> <com.google.android.material.appbar.MaterialToolbar android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary"/> </com.google.android.material.appbar.AppBarLayout> <!-- 你的FrameLayout容器,加上behavior属性就搞定了 --> <FrameLayout android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="这里是你的文本内容"/> </FrameLayout> </androidx.coordinatorlayout.widget.CoordinatorLayout>
方案2:直接组合状态栏和ActionBar高度属性
要是你不想用CoordinatorLayout,也可以直接用系统自带的?attr/statusBarHeight属性拿到状态栏高度,然后通过内外边距叠加的方式实现总偏移(XML里没法直接把两个属性值相加,但内外边距加起来的效果是一样的)。
示例代码:
<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- 你的Toolbar,先让它定位在状态栏下方 --> <com.google.android.material.appbar.MaterialToolbar android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:layout_marginTop="?attr/statusBarHeight"/> <!-- TextView的总顶部偏移 = 状态栏高度 + ActionBar高度 --> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="这里是你的文本内容" android:layout_marginTop="?attr/actionBarSize" android:paddingTop="?attr/statusBarHeight"/> </FrameLayout>
另外补充一点:?attr/statusBarHeight是系统提供的适配属性,会自动根据不同设备调整高度(比如全面屏和普通手机的状态栏高度不一样),比硬写dp值灵活多了。要是你觉得内外边距的方式有点绕,也可以自己定义dimen资源,但硬编码的方式不推荐,不如前两种方案靠谱。
内容的提问来源于stack exchange,提问作者Jim Clermonts
相关产品推荐
相关产品推荐

