当我切换到 RelativeLayout 时,我在设计中放入的所有内容都会显示在屏幕的左上角

When I switch to RelativeLayout, everything I put in the designs shows up in the top left corner of screen

我在 Android 工作室中从 ConstraintLayout 切换到 RelativeLayout,现在我在设计中放入的所有内容都出于某种原因显示在左上角。

我可以在Design中拖动并重新定位它,但是写填充非常耗时且令人厌烦。我什至将默认值更改为 RelativeLayout 但没有任何变化。

    <?xml version="1.0" encoding="utf-8"?>
   <RelativeLayout 
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="match_parent" 
   android:layout_height="match_parent">

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

我想通过在屏幕上拖动它们来重新定位它们,而不是将它们卡在屏幕的左上角。

是的,这是 RelativeLayout 的 属性。

RelativeLayout需要你说出widget之间的位置关系。如果不指定所有widgets的位置关系,那么所有widgets都会折叠到parent的(0, 0),结果就是你看到的,

everything I put in the design shows up in the top left.

指定widget之间的关系,可以使用android:layout_*系列属性,例如:

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" /> <!-- this will at top left -->

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/textView"
    android:text="Button" /> <!-- this will at right of textView -->

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toBottomOf="@id/button"
    android:text="TextView" /> <!-- this will below button -->

您可以尝试在 Design Layout 中指定它们,但我发现这有点困难。

  1. 点击一个小部件,然后这个小部件周围会出现圆圈。
  2. 点击一个圆圈,稍等。所有小部件周围都会有圆圈。
  3. 将这个圆圈拖到另一个小部件的圆圈,如果您使用 ConstraintLayout,这将在它们之间建立联系。
  4. 但是,如果您使用 RelativeLayout,似乎不可能这样做,因为所有小部件都折叠到相同的位置。

有关详细信息,请参阅 Android Guide to RelativeLayout