ConstraintLayout TextView显示不全的处理

1,807 阅读1分钟

不断踩坑,不断超越

很喜欢用RelativeLayout,无奈,RelativeLayout会测量2次,且有时还要嵌套多层,导致测量测试翻倍

来着优化UI的原则,建议使用 FrameLayout > LinearLayout > ConstraintLayout, 尽量是嵌套一层

尽量不使用RelativeLayout

然而ConStrainLayout使用起来并不想RelativeLayout那么简单

我想设置一下两个TextView并列显示,当一个TextView过长时,显示...

所以我的设置如下

<?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:orientation="vertical">

    <TextView
        android:id="@+id/tv_video_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="留住美好的瞬间留住美好的瞬间留住美好的瞬间"
        android:textSize="26dp"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toStartOf="@id/tv_more"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/tv_more"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="更多更多更多更多更多更多更多"
        app:layout_constraintBaseline_toBaselineOf="@+id/tv_video_name"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

当tv_video_name过长时,显示效果如下:

image.png

当tv_video_name过短时,显示如下:

image.png

都不符合想要的效果,

三种解决方案

  1. 修改如下,把tv_video_name的layout_width设置为0dp

  2. tv_video_name的layout_width还是wrap_content, 增加两个属性

app:layout_constrainedWidth="true"
app:layout_constraintHorizontal_bias="0"
  1. tv_video_name的layout_width设成match_parent, 增加一个属性
app:layout_constrainedWidth="true"

显示为

image.png

image.png