android - 将 View 底部与文本基线对齐

标签 android android-constraintlayout android-layout

在 ConstraintLayout 中,有没有办法将 View(例如 ImageView)的底部与 TextView 的基线对齐?我希望有一个像 app:layout_constraintBottom_toBaselineOf 这样的约束,但不存在这样的约束。

注意:我试过 app:layout_constraintBaseline_toBaselineOf,但看起来只有在 TextView 上定义时才有效。

最佳答案

这可能为时已晚,但我希望对阅读这篇文章的人仍然有帮助。

在这个具体的例子中,如果你想将 ImageView 对齐到 TextView 的基线,ImageView 的默认对齐设置应用于“顶部”,不知道为什么。很可能你想将它应用于 ImageView 的底部,这可以通过设置 android:baselineAlignBottom="true" 属性。更多信息在这里:https://developer.android.com/reference/android/widget/ImageView.html#attr_android:baselineAlignBottom

ConstraintLayout 的完整代码如下所示:

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
  <TextView
      android:id="@+id/textView"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content" />
  <android.support.v7.widget.AppCompatImageView
      android:id="@+id/imageView"
      android:layout_width="96dp"
      android:layout_height="96dp"
      android:baselineAlignBottom="true"
      app:layout_constraintBaseline_toBaselineOf="@id/textView"
      app:layout_constraintStart_toEndOf="@id/textView"
      app:srcCompat="@drawable/drawable1"
      android:contentDescription="@null"/>
</android.support.constraint.ConstraintLayout>

我在我的项目中使用了 AppCompatImageView,但我很确定常规 ImageView 的工作方式相同。

RelativeLayout 也可以通过向 ImageView 添加 layout_alignBaseline="@id/textView" 来实现相同的行为。

如果由于某种原因这不起作用,例如您有自定义 View 或其他东西,您也可以考虑在运行时进行。

TextView 中有一个方法,叫做 getLastBaselineToBottomHeight。它返回最后一个文本基线与此 TextView 底部之间的距离。您可以将该值应用于您的 View 的底部边距,这应该会产生相同的效果。虽然该方法仅在 Android P 中引入,但您可以按照相同的方式简单地实现它(根据源代码)。只是一个对我有用的例子:

MarginLayoutParams params = (MarginLayoutParams) rootView.findViewById(R.id.imageView).getLayoutParams();
params.bottomMargin = textView.getPaddingBottom() + textView.getPaint().getFontMetricsInt().descent;

希望对您有所帮助。祝你好运!

关于android - 将 View 底部与文本基线对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46260589/

相关文章:

android - 创建自定义样式会导致应用程序崩溃

java - 将自定义TensorFlowLite模型添加到就绪的Android应用程序时出现问题

Android:ConstraintLayout 在 SDK 4.1.x 上有不同的行为

android - 现在,蓝图 View 和约束在 Android Studio 设计 View 中均不可见

android - 如何在android中获取显示图像的宽度和高度?

android - 按钮中的 onClick 不起作用使用数据绑定(bind)

android - 在约束布局中切换链组的可见性

android - 设计排版显示不一样

android - 在 NestedScrollView 中使用 ListViews 的正确替代方法是什么?

android - 更改图标的颜色与制作多种颜色的图标