Android布局 - 两个视图彼此相邻,宽度相等,使用全屏宽度

时间:2014-11-14 12:45:36

标签: android android-layout view android-layout-weight

我在android中遇到布局问题。我希望两个视图应该具有相同的宽度,并且它们应该几乎使用屏幕的整个宽度。每个视图都应包含一个居中的标签。

完成后应该看起来像这样:

Example

这是我到目前为止所做的:

<?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">

        <View
            android:id="@+id/view1"
            android:layout_width="10dp"
            android:layout_height="90dp"
            android:layout_alignParentTop="true"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="10dp" />

        <View
            android:id="@+id/view2"
            android:layout_width="10dp"
            android:layout_height="90dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_marginTop="10dp"
            android:layout_marginRight="10dp" />

    </RelativeLayout>

我现在只有宽度的占位符值。

感谢。

3 个答案:

答案 0 :(得分:10)

你必须在xml中使用android:layout_weight属性所以尝试下面的代码希望它能解决你的问题: -

 <LinearLayout
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     android:orientation="horizontal">

     <Button
        android:text="Register"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_margin="5dp"
        android:layout_weight="1" />

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_margin="5dp"
        android:layout_weight="1" />

  </LinearLayout>
  

创建一个线性布局,其中每个孩子使用相同数量的   屏幕上的空格,设置每个视图的android:layout_height   &#34; 0dp&#34; (对于垂直布局)或每个视图的android:layout_width   to&#34; 0dp&#34; (用于水平布局)。然后设置android:layout_weight   每个视图到&#34; 1&#34;

For more info you need to read Linear layout.

答案 1 :(得分:1)

使用LinearLayout会更容易,将布局设置为match_parent horizontal方向。

之后,在layout_width中将0px设置为layout_weight=1view

请参阅此说明:

Layout buttons so each divides up the space equally

答案 2 :(得分:0)

你必须使用layout_weight属性。

     <Button
        android:text="Register"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_margin="5dp"
        android:layout_weight="1" />

     <Button
        android:text="Not this time"
        android:id="@+id/cancel"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:padding="10dip"
        android:layout_margin="5dp"
        android:layout_weight="1" />

  </LinearLayout>
相关问题