android - 相对布局在左上角添加所有元素
问题描述
我添加了一个相对布局资源文件,每当我拖放一个元素时,它都会被设置到左上角。有任何解决这个问题的方法吗?
这是代码:
<?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">
<Button
android:id="@+id/button5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<Switch
android:id="@+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Switch" />
</RelativeLayout>
解决方案
您可以添加属性android:gravity="center"
来对齐里面的子元素RelativeLayout
。这将使子元素与布局的中心对齐。此外,android:layout_centerInParent="true"
您可以使用android:layout_alignParentTop="true"
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<!-- you need to align the button to a particular
place in the layout -->
<Button
android:id="@+id/button5"
android:layout_centerInParent="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button"
android:layout_margin="10dp"/>
<!-- Then add layout_below/layout_above -->
<Switch
android:id="@+id/switch1"
android:layout_below="@id/button5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Switch Number 1"
android:layout_margin="10dp"/>
</RelativeLayout>
您还可以设置多个值:android:gravity="bottom|right"
。这会将孩子对齐到右下角。最后的话:了解RelativeLayout
一下它以及如何使用它。
推荐阅读
- reactjs - 如何在 VS 代码上隐藏这些标签?
- project-reactor - Spring Reactor Mono 或 Flux,如何获得第一个信号但仍让其余信号通过?
- java - 如何在 scala/java 项目中使用 aar maven 依赖项
- python - 使用 NumPy 将 3D 函数映射到网格网格的有效方法
- python - 使用 multiprocessing.pool.map 将 kwargs 传递给 pandas Dataframe 的函数
- c# - URL 字符串的正确格式
- r - addCircles 需要非 NULL 纬度和经度值
- c# - 使用 C# Fluent Validation,是否可以创建自定义错误消息来说明特定集合成员失败的原因?
- java - 同一 JPanel Java Swing GUI 中的相邻 JTextField
- javascript - 如何允许在 mouseenter/mouseleave 悬停 div 中单击而不关闭它?