Android中如何创建垂直布局
在Android中创建垂直布局可使用LinearLayout还是ConstraintLayout。以下是使用LinearLayout创建垂直布局的示例代码:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView 1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView 2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
在上面的示例中,我们创建了一个垂直方向的LinearLayout,然后在其中添加了一个TextView、另外一个TextView和一个Button,它们会依照垂直方向顺次排列。LinearLayout的orientation属性设置为"vertical"表示垂直布局。
除LinearLayout,你也能够使用ConstraintLayout来创建垂直布局。以下是使用ConstraintLayout创建垂直布局的示例代码:
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView 1"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView 2"
app:layout_constraintTop_toBottomOf="@id/textView1"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintTop_toBottomOf="@id/textView2"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
在上面的示例中,我们创建了一个垂直方向的ConstraintLayout,然后使用ConstraintLayout中的束缚属性将TextView和Button顺次垂直排列。这类方式更加灵活,可以更精确地控制视图的位置和大小。
TOP