▼問題
ScrollViewのheightをwrapcontentにしたところ制約を守らず、文字が溢れてしまった。
・理想
・今回
(ScrollViewそのもの自体が伸びて、ほかのViewに覆い被さっています)
一応コードはこんな感じです
<androidx.constraintlayout.widget.ConstraintLayout ~省略~>
<TextView
android:id="@+id/view_1"
android:layout_width="match_parent"
android:layout_height="400dp"
android:gravity="center|bottom"
android:text="↓ここまでViewがある"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="@+id/view_2"
android:layout_width="match_parent"
android:layout_height="400dp"
android:gravity="center|top"
android:text="↑ここまでViewがある"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/purple_200"
app:layout_constraintBottom_toTopOf="@id/view_2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/view_1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="top\n1\n2\n3\n4\nbottom" />
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
実際は、制約はちゃんとついているのですが、wrap_contentが優先されて
あたかも制約を守っていないように見えています。
▼解決
ScrollViewのattributeに「layout_constrainedHeight="true"」を追加する。
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@color/purple_200"
app:layout_constrainedHeight="true"
app:layout_constraintBottom_toTopOf="@id/view_2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/view_1">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="top\n1\n2\n3\n4\nbottom" />
</ScrollView>
このattributeを追加することで制約を忠実に守り、文字が溢れるのを防ぐことができます。
layout_constrainedWidthで横の制約を守らせることもできます。
最後に
レイアウトデザインをするうえでかなり便利です。
溢れる可能性があるときは、使用することがおススメです。