Android布局技术求助:垂直LinearLayout中TextView设置wrap_content高度时max_lines属性不生效的解决方法
解决LinearLayout中TextView的行数限制与剩余空间填充问题
我来帮你搞定这个布局难题!你遇到的核心问题其实是两个小细节没处理对,咱们一步步来解决:
方案一:用LinearLayout实现(最贴合你的初始需求)
你之前的问题出在第二个TextView的layout_weight设置上——设为0的话它根本不会填充剩余空间!另外,maxLines在wrap_content下是生效的,可能你没搭配ellipsize(可选但推荐),或者有其他冲突属性(比如singleLine="true"会覆盖maxLines)。
正确的布局代码如下:
<LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <!-- 书籍标题:自适应高度但最多3行 --> <TextView android:id="@+id/tv_book_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:maxLines="3" android:ellipsize="end" <!-- 超出3行时显示省略号,可选 --> android:text="这里可以放很长的书籍标题,比如《Android布局实战从入门到精通:解决各种复杂布局场景的100个技巧》"/> <!-- 作者信息:填充剩余空间 --> <TextView android:id="@+id/tv_book_author" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" <!-- 关键:设为1才能占据剩余空间 --> android:text="作者:张三 | 出版社:技术出版社 | 出版时间:2024年6月"/> </LinearLayout>
为什么这样可行?
- 标题TextView的
wrap_content会根据文本长度自适应高度,但maxLines="3"会限制它最多只占3行的高度,内容短的时候就只占对应行数的空间,不会出现多余间距。 - 作者TextView用
0dp+layout_weight="1",会自动填充LinearLayout中标题下方的所有剩余空间,而且会紧紧跟着标题,不会有间隙。
方案二:用ConstraintLayout实现(解决你之前转换失败的问题)
如果你想用ConstraintLayout,只要约束关系设置正确就能生效,核心是让作者TextView的顶部贴紧标题底部,底部贴紧父布局底部,高度设为0dp:
<androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <TextView android:id="@+id/tv_book_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:maxLines="3" android:ellipsize="end" android:text="很长的书籍标题测试内容,确保最多显示3行" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> <TextView android:id="@+id/tv_book_author" android:layout_width="match_parent" android:layout_height="0dp" android:text="作者:李四 | 简介:专注Android开发10年,著有多本技术畅销书" app:layout_constraintTop_toBottomOf="@id/tv_book_title" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout>
这个写法里,标题的maxLines="3"同样会生效,作者TextView会自动填充标题到父布局底部的所有空间,完全符合你的需求。
内容的提问来源于stack exchange,提问作者MichiBros
相关产品推荐
相关产品推荐

