除非重叠的textview是否有可能使图标在约束布局中居中

时间:2019-05-31 12:07:19

标签: android android-constraintlayout

我试图使图标始终位于约束布局内,同时使其始终停留在约束布局底部的某些文本视图上(这是我实际问题的非常简化的版本,但同样代表了问题) 。底部的文本可能足够大,可以越过版式的中心,在这种情况下,我希望图标向上移动。

为了使图标的底部与中心以及文本视图的顶部相关联,我在布局的中心使用了一条指导线,并设置了一个障碍物来捕捉文本视图的顶部或指导线的顶部(以较高者为准)更高。

问题在于图标的一半位于准则之下,因此文本仍然被图标覆盖。并且仅当文本视图的顶部超过准则时,图标才会向上移动。另外,我可以将图标的底部设置在准则的顶部,这样文本视图就不会重叠,但是图标却不能精确居中。

这是具有所有项目的布局的当前状态:

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="200dp">

    <ImageView
        android:layout_width="40dp"
        android:layout_height="40dp"
        android:src="@drawable/ic_play"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="@id/barrier"
        app:layout_constraintBottom_toBottomOf="@id/barrier"
        />

    <androidx.constraintlayout.widget.Barrier
        android:id="@+id/barrier"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:barrierDirection="top"
        app:constraint_referenced_ids="guide,text" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guide"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5"/>

    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Temporibus ea quasi ut dolores quae qui. Et dolor sit voluptatem fugit. Possimus nulla molestias maxime. Distinctio perferendis veniam modi sint numquam dolores esse. Minus consequuntur mollitia asperiores praesentium non minus. Temporibus ea quasi ut dolores quae qui. Et dolor sit voluptatem fugit. Et dolor sit voluptatem fugit."
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

我发现了一个(不太好的)解决方案,该解决方案是在文本视图中添加顶部填充,其大小为图像视图的一半。我宁愿避免这种黑客攻击,而是找到一个好的实现。有可能吗?

为帮助理解该问题,以下是Android Studio中的UI设计器提供的一些图像:

带有短文本的希望结果: Icon centered, short text not overlapped

当文本较长时会引起问题: Icon shifted upwards, long text overlapped

如果文本较短时图标未居中: Icon not centered, short text not overlapped

文本较长时,我们不会遇到问题: Icon shifted upwards, long text not overlapped

1 个答案:

答案 0 :(得分:0)

paddingTop的{​​{1}}设置为TextView的一半

ImageView