我最近开始学习Android开发。我正在使用 Android Studio,并用它创建了 XML 布局文件。但模拟器上的布局看起来与我在 XML 上创建的布局不同,我不知道为什么会发生这种情况。
这是我的主要事件布局的图片:
这是我的模拟器的图片:
纯文本应该位于 TextView 下方,但在模拟器中,它的位置不同(我已将错误标记为红色)。
这是主要事件的代码:
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="208dp"
android:text="SUBMIT"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="80dp"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="44dp"
android:text="Enter the value in kg below"
android:textSize="25sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<EditText
android:id="@+id/editTextNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number"
tools:layout_editor_absoluteX="100dp"
tools:layout_editor_absoluteY="73dp" />
最佳答案
我不确定为什么它在模拟器中与预览中以这种方式显示,但 EditText 字段不是您想要的位置的原因是您如何设置 editTextNumber
字段的位置:
tools:layout_editor_absoluteX="100dp"
tools:layout_editor_absoluteY="73dp"
您告诉 Android 将字段定位在距屏幕顶部 100 像素、向下 73 像素的位置。发生这种情况很可能是因为您不小心在编辑器窗口中稍微拖动了该字段,该字段指定了确切的像素位置。
相反,由于您使用的是 ConstraintLayout,因此您需要设置 EditText 相对于布局上其他字段的位置。例如,删除上面的两行并将其替换为如下内容:
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView"
我还建议您在布局上命名字段并描述它们所代表的内容,而不是默认值 textView
和 textView2
。例如,考虑将 textView2
更改为类似 weight_label_textview
的内容。这将使您更容易知道您在布局和代码中处理哪个字段。
关于android-studio - Android 模拟器中的布局与布局文件相比看起来有所不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67450279/