在ConstraintLayout中,是否有一种方法可以将视图的底部(例如ImageView)与TextView的基线对齐?我预计会有像app:layout_constraintBottom_toBaselineOf
这样的约束,但这种约束是不存在的。
注意:我尝试过app:layout_constraintBaseline_toBaselineOf
,但它似乎只有在TextView上定义时才有效。
发布于 2018-03-14 12:04:24
这可能已经太迟了,但我希望仍能对阅读这篇文章的人有所帮助。
在这个特定的示例中,如果您想要将ImageView
与TextView
的基线对齐,则将ImageView
的默认对齐设置应用于"top",不确定为什么.很可能要将其应用到ImageView
的底部,这可以通过设置android:baselineAlignBottom="true"
属性来实现。
因此,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"
来实现相同的行为。
如果由于某些原因(例如,您有一个自定义视图或其他东西)无法工作,您也可以考虑在运行时执行该操作。
TextView
中有一个名为getLastBaselineToBottomHeight
的方法。它返回最后一个文本基线到这个TextView
底部之间的距离。您可以将该值应用于您的View
的底部边距,这将给您带来同样的效果。尽管该方法仅在Android中引入,但您可以使用相同的方式实现它(根据源代码)。仅举一个对我有用的例子:
MarginLayoutParams params = (MarginLayoutParams) rootView.findViewById(R.id.imageView).getLayoutParams();
params.bottomMargin = textView.getPaddingBottom() + textView.getPaint().getFontMetricsInt().descent;
我希望这能帮上忙。祝好运!
https://stackoverflow.com/questions/46260589
复制相似问题