我得到了这个设置:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:layout_width="0dp"
android:layout_height="0dp"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
app:layout_constraintBottom_toTopOf="@+id/guideline"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.constraint.Guideline
android:id="@+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.35" />
...
</android.support.constraint.ConstraintLayout>
</ScrollView>
现在,当 View 未满并且不需要滚动条时 - 一切都按预期工作 - 图像相对于屏幕尺寸为 35%。但随着图像下方出现更多内容,就出现了对滚动条的需求,并且指南的 0.35% 的 constrainGuide 似乎是根据屏幕的整个长度(而不是物理长度)计算的,因此随着 View 变得“更长”,ImageView 也会变得更大。 有没有办法避免这种情况并且始终具有物理屏幕尺寸的 x%?
最佳答案
您指定的引用线放置在距离 ConstraintLayout
顶部一定百分比的位置。不幸的是,对于您的应用程序,指南与 View 的整体高度相关,而不是与屏幕的百分比相关。因此,如果 ConstraintLayout
高于分配给它的屏幕尺寸,您将看到这种变化。请参阅documentation 指南
。
Positioning a Guideline is possible in three different ways:
- specifying a fixed distance from the left or the top of a layout (layout_constraintGuide_begin)
- specifying a fixed distance from the right or the bottom of a layout (layout_constraintGuide_end)
- specifying a percentage of the width or the height of a layout (layout_constraintGuide_percent)
您可以以 dp
为单位指定距布局顶部的静态偏移量,但这无法适应不同的屏幕尺寸。我不相信仅仅使用 XML 就有解决方案。
但是,您可以计算代码中的像素数并在运行时设置距离。您需要将 Guideline
更改为与布局顶部的固定距离,计算与顶部的距离,然后调用 setGuidelineBegin
放置引用线。
setGuidelineBegin
void setGuidelineBegin (int guidelineID, int margin)
Set the guideline's distance form the top or left edge.
关于android - ConstraintLayout Guideline 与 View 一起扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49286762/