【问题标题】:First time programmer confused as to why the EditText and Button fields aren't going where I want them to第一次程序员对为什么 EditText 和 Button 字段没有去我想要的地方感到困惑
【发布时间】:2015-06-20 12:07:31
【问题描述】:

我在 android studios 上用 XML 编码,我无法让 EditText 居中在顶部,而 Button 居中在中心。我对代码知之甚少,所以我读过的关于相对布局与线性布局的其他内容非常令人困惑。在此之前我从未编写过代码,所以如果大部分内容有误,我非常抱歉。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"

android:orientation="horizontal"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:id="@+id/touch" >

<EditText android:id="@+id/edit_message"
    android:layout_width="225dp"
    android:layout_height="225dp"
    android:layout_gravity="center"
    android:hint="@string/edit_message"
    />

<TextView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="top"
    android:textSize="62sp"
    android:text="@string/begin_app"/>

</LinearLayout>

【问题讨论】:

  • 如果你想让你的线性布局方向垂直,如果你想让一个在另一个之下。也许添加一张你想要实现的图片......

标签: android xml textview android-linearlayout android-relativelayout


【解决方案1】:

在您的布局中使用以下代码:

android:layout_alignParentTop 将在顶部对齐视图

android:layout_alignParentTop 会将视图对齐到父级的中心

android:layout_centerHorizontal="true"android:layout_centerVertical="true" 会将视图对齐到父视图的中心

带有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"
    android:orientation="vertical">

    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:text="text" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="Button" />
</RelativeLayout>

在 android studio 中只需转到布局 xml 文件并单击设计,您可以将小部件拖放到您想要的任何位置,系统会为您生成代码并放置在您想要的位置。它非常适合初学者。

【讨论】:

  • 哇,效果很好!太感谢了。如果我在设计中移动它,我不知道代码会调整,谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-22
  • 1970-01-01
  • 2018-12-03
  • 2020-05-14
  • 2012-07-18
  • 1970-01-01
相关资源
最近更新 更多