我正在尝试在我的 Android 应用程序上实现以下布局:
如您所见,我想要一个中央登录框,占据大约 70% 的宽度。我相信基本上有两种方法可以实现这一目标:
1.为登录框创建线性或相对布局,并在左侧和右侧添加layoutMargin。
2. 创建一个weightSum="1"的包装器LinearLayout,然后将RelativeLayout 放置在其中,layout_width="0dp"和layout_weight="0.7"。
使用第一种方法,XML 将如下所示:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/logo"
android:contentDescription="@string/logo"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#999999"
android:gravity="center"
android:layout_margin="30dp"
>
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:hint="@string/email" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:hint="@string/password" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/login"/>
</LinearLayout>
</LinearLayout>
第二种方法只是在当前的 LinearLayout 之上有一个包装器 LinearLayout,其weightSum=“1”,并且内部布局将获得一个layout_weight=“0.7”属性。
您认为哪一种是最好的方法?提前致谢。
最佳答案
一种相当简单的方法是在相对布局中使用线性布局。然后使用layout_centerInParent并将其设置为“true”。完成后,您可以将边距设置为您想要的任何值(我使用 30 dp)。这是一个例子:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="30dp"
android:orientation="vertical"
android:weightSum="50" >
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:inputType="textEmailAddress" >
<requestFocus />
</EditText>
<EditText
android:id="@+id/editText2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editText1"
android:layout_centerHorizontal="true"
android:inputType="numberPassword" />
<Button
android:id="@+id/button1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@id/editText2"
android:layout_centerHorizontal="true"
android:text="Button" />
</LinearLayout>
</RelativeLayout>
当然,如果您希望登录框的宽度恰好是屏幕宽度的 70%,您可以通过编程来实现。
关于Android:什么时候使用layout_margin,什么时候使用weightSum?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12864359/