EditText高度增长时如何让ListView自动上滑避免被遮挡
问题原因
- 根布局使用
FrameLayout时所有子控件按层叠顺序摆放,你给ListView外层容器设置了固定paddingBottom=50dp仅适配EditText初始高度,当EditText输入多行文本身高增长后,固定的底部边距不会同步变化,就会出现ListView底部被遮挡的问题。 - 代码中给EditText设置的
layout_alignParentBottom是RelativeLayout的专属布局属性,放在FrameLayout下不会生效,也是布局逻辑异常的原因之一。
修复方案
改动最小的布局调整
将根布局替换为RelativeLayout,给ListView外层容器增加layout_above属性绑定到EditText,就能让ListView区域自动跟随EditText的高度变化调整自身底部位置,不会再被遮挡。修改后的完整布局如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:paddingTop="18dp" android:paddingBottom="18dp" android:text="send" android:id="@+id/button_send" android:layout_width="60dp" android:layout_height="52dp" android:layout_alignParentBottom="true" android:layout_alignParentRight="true"/> <EditText android:id="@+id/mainEditText" android:background="#EBEBEB" android:hint="Type your message here..." android:layout_width="fill_parent" android:layout_height="wrap_content" android:ems="10" android:inputType="textMultiLine|textCapSentences" android:maxLines="8" android:minHeight="48dp" android:minLines="1" android:paddingLeft="10dp" android:smoothScrollbar="true" android:scrollbars="vertical" android:scrollHorizontally="false" android:layout_alignParentBottom="true" android:layout_marginRight="60dp"/> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/mainEditText" android:orientation="vertical"> <ListView android:id="@+id/messages_view" android:layout_width="match_parent" android:layout_height="match_parent" android:divider="@null" android:dividerHeight="0dp" android:listSelector="@android:color/transparent" android:stackFromBottom="true" android:transcriptMode="normal"/> </RelativeLayout> </RelativeLayout>
可选交互优化
如果需要EditText高度增长时,ListView自动滚动到最新消息位置,可以在Activity/Fragment中给EditText添加布局变化监听:
// Kotlin 示例代码 mainEditText.addOnLayoutChangeListener { _, _, _, _, bottom, _, _, _, oldBottom -> if (bottom != oldBottom) { // 高度变化时滚动ListView到最后一项 messages_view.adapter?.let { adapter -> messages_view.smoothScrollToPosition(adapter.count - 1) } } }
内容的提问来源于stack exchange,提问作者Gamer_ John Angelo
相关产品推荐
相关产品推荐

