Android Kotlin实现:字符增多时TextView标题上移且不偏移描述
实现方案
可以通过ConstraintLayout实现这个需求,核心逻辑是固定Description的位置,让Title的底部与Description顶部建立约束,使Title根据内容长度向上扩展,同时不干扰Description的位置。
布局代码示例
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout 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="wrap_content" android:padding="16dp"> <!-- Description 固定位置,不受Title内容影响 --> <TextView android:id="@+id/tv_description" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="固定描述内容" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent"/> <!-- Title 底部绑定到Description顶部,内容变长时自动向上扩展 --> <TextView android:id="@+id/tv_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="短标题" android:textSize="18sp" android:textStyle="bold" app:layout_constraintBottom_toTopOf="@id/tv_description" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintVertical_bias="1.0"/> </androidx.constraintlayout.widget.ConstraintLayout>
关键说明
tv_description通过app:layout_constraintBottom_toBottomOf="parent"固定在布局底部(也可根据需求约束到其他固定位置),确保位置稳定。tv_title的layout_constraintVertical_bias="1.0"让短标题默认紧贴Description上方;当标题内容变长时,由于高度设为wrap_content,会自动向上延伸,不会挤压Description偏移。
内容的提问来源于stack exchange,提问作者onesector
相关产品推荐
相关产品推荐

