我刚刚开始学习应用程序开发,我使用constraintlayout的.xml文件的设计选项卡在屏幕中央创建了一个带有2个按钮的应用程序,1个在另一个下面。但是当我在我的设备上运行它时,只显示第二个按钮,它也在左上角。有人可以帮助我(初学者)。另请告诉我如何将其更改为相对布局!
截图
答案 0 :(得分:0)
创建新布局文件时获得的默认布局称为ConstraintLayout
。如果您想在其中放置任何视图(Buttons
,TextViews
等),则必须将它们限制在其他视图或窗口中,否则它们会跳到左上角在您的申请中。
我假设您刚刚在图形设计器中添加了2 Buttons
并将它们放在布局的中心而没有将它们限制为任何东西,因此在xml文件中它们应该看起来像这样:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
tools:layout_editor_absoluteX="132dp"
tools:layout_editor_absoluteY="156dp" />
当您将鼠标悬停在<Button
上时,如果没有约束,Android Studio应该会显示警告。 xml的最后两行用于在设计器中定位视图,但它们不能反映应用程序内部的定位。如果您想定位视图,则必须将它们限制为其他视图,如下所示:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
/>
按钮现在在所有4个边上被约束到它的父级,这意味着它将在其父级内部水平和垂直居中。具有2个居中按钮的布局可能如下所示:
<Button
android:id="@+id/topButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Top button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toTopOf="@id/bottomButton"
app:layout_constraintVertical_chainStyle="packed"
/>
<Button
android:id="@+id/bottomButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Bottom button"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="@id/topButton"
app:layout_constraintBottom_toBottomOf="parent"
/>
正如您所看到的,Buttons
相互约束。如果您想使用RelativeLayout
,只需将xml文件的根布局从android.support.constraint.ConstraintLayout
更改为RelativeLayout
。
我个人建议学习如何使用ConstraintLayout
,因为它是最强大的布局,也是Google试图让每个人都使用的布局。