ConstraintLayout垂直对齐项目顶部

时间:2020-06-03 15:07:09

标签: android android-recyclerview android-constraintlayout

我在ConstraintLayout中有一个简单的RecyclerViewConstraintLayout仅包含图像和文本。

<?xml version="1.0" encoding="utf-8"?>
<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/gridRv"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_marginTop="16dp"
  android:layout_marginLeft="@dimen/size_8dp"
  android:layout_marginRight="@dimen/size_8dp"
  android:layout_marginBottom="@dimen/size_8dp"/>
<?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:id="@+id/linearLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/size_16dp"
    android:paddingBottom="@dimen/size_16dp"
    android:paddingLeft="@dimen/size_8dp"
    android:paddingRight="@dimen/size_8dp"
    android:background="@drawable/grid_item_state">

  <ImageView
      android:id="@+id/gridImage"
      android:layout_width="0dp"
      android:layout_height="0dp"
      android:layout_marginBottom="12dp"
      android:scaleType="centerCrop"
      app:layout_constraintBottom_toTopOf="@+id/gridText"
      app:layout_constraintDimensionRatio="1:1"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toTopOf="parent"
      app:layout_constraintVertical_chainStyle="spread_inside"
      app:layout_constraintWidth_percent="0.45" />

  <TextView
      android:id="@+id/gridText"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:fontFamily="@font/montserrat_regular"
      android:hint="@string/global_option"
      android:textColor="@color/blue_600"
      android:textFontWeight="400"
      android:maxLines="4"
      android:gravity="top|center_horizontal"
      app:layout_constraintBottom_toBottomOf="parent"
      app:layout_constraintEnd_toEndOf="parent"
      app:layout_constraintStart_toStartOf="parent"
      app:layout_constraintTop_toBottomOf="@id/gridImage" />

</androidx.constraintlayout.widget.ConstraintLayout>

此代码产生以下内容: heigh:wrap_content

我希望文本垂直对齐到顶部。文本需要在图片之后立即开始(带有少量空白)。

当我将TextView的高度更改为android:layout_height="0dp"时,几乎可以得到想要的结果。这里的问题是TextView无法缩放以包含整个文本。

height:0dp

我理解为什么会有这个问题。这是因为我使用了app:layout_constraintVertical_chainStyle="spread_inside"。我可以改用LinearLayout,但我想要ConstraintLayout,因为我需要图像在保持一定百分比宽度的同时保持其宽高比。

你们有什么建议要达到我想要的结果吗?

1 个答案:

答案 0 :(得分:1)

我想您需要从app:layout_constraintBottom_toBottomOf="parent"中删除TextView,以使文本在顶部与顶部图像对齐