使用AppBarLayout时EditText被移至布局底部的问题
搞定AppBarLayout下EditText跑底部、FAB位置偏移的问题
嘿,我太懂这种布局调半天不对头的糟心了!咱们先理清楚问题根源:CoordinatorLayout 是个靠Behavior驱动的布局,你的EditText没配上合适的行为约束,就被AppBarLayout的默认逻辑挤到屏幕底了;FAB的位置跑偏,也大概率是锚点或者Behavior没设置对。
1. 把EditText牢牢钉在Toolbar下方
核心就是给EditText的容器(或者直接给EditText)加上app:layout_behavior="@string/appbar_scrolling_view_behavior"——这是Material库专门给滚动View准备的Behavior,能让它紧紧跟着AppBarLayout的底部走,不会被挤飞。
给你改好的布局示例(如果用AndroidX的话记得把包名换成com.google.android.material):
<?xml version="1.0" encoding="utf-8"?> <android.support.design.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"> <!-- AppBarLayout 区域 --> <android.support.design.widget.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/AppTheme.AppBarOverlay"> <android.support.v7.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" app:popupTheme="@style/AppTheme.PopupOverlay"/> </android.support.design.widget.AppBarLayout> <!-- 用NestedScrollView包裹EditText,支持滚动,同时加上关键Behavior --> <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <EditText android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="在这里输入内容" android:layout_marginStart="16dp" android:layout_marginEnd="16dp" android:layout_marginTop="16dp"/> </android.support.v4.widget.NestedScrollView> <!-- 修正FAB的位置:锚定到AppBarLayout,设置好重力 --> <android.support.design.widget.FloatingActionButton android:id="@+id/fab" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="16dp" app:layout_anchor="@id/appbar" app:layout_anchorGravity="bottom|right|end" android:src="@drawable/ic_add"/> </android.support.design.widget.CoordinatorLayout>
2. 几个必须注意的关键点
app:layout_behavior不能少:哪怕你不用NestedScrollView,用LinearLayout或者ConstraintLayout包裹EditText,也要给这个容器加上这个Behavior,否则CoordinatorLayout不知道怎么安排它的位置。- FAB要锚定到正确的View:通过
app:layout_anchor指定锚定的AppBarLayout(或者Toolbar),再用app:layout_anchorGravity设置相对位置,这样它的位置就会和锚定View联动,不会乱跑。 - 如果用AndroidX,替换包名:把所有
android.support.design.widget换成com.google.android.material,比如com.google.android.material.appbar.AppBarLayout,同时确保build.gradle里引入了Material库:
implementation 'com.google.android.material:material:1.9.0'
3. 排查小技巧
如果还是不对,检查这几个坑:
- 别给EditText加
layout_gravity="bottom"或者layout_alignParentBottom="true",这会直接把它推到底部。 - AppBarLayout的
layout_height别设成match_parent,用wrap_content或者固定高度(比如?attr/actionBarSize)就行。 - 确认你的主题里没有影响布局的奇怪属性,比如给AppBarLayout加了额外的margin或者padding。
内容的提问来源于stack exchange,提问作者user9550968
相关产品推荐
相关产品推荐

