Android RelativeLayout布局属性应用

来源:互联网 发布:warframe网络端口设置 编辑:程序博客网 时间:2024/04/27 18:52

目标:
写一个应用界面,以RelativeLayout实现,效果如下:
这里写图片描述

文字一和文字二水平对齐,居中,各自距离左右边界相同的距离,中间相隔10dp。文字二距离边界20dp(即文字到蓝色边界的距离)。
先实现layout(这里用到的颜色都是color.xml里定义的):

<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"    android:background="@color/green"    android:gravity="center" ></RelativeLayout>

这里使用了android:gravity=”center”表示子控件处于父控件的中心部位。

然后在里面加入两个文本框,先加文本一:

    <TextView        android:id="@+id/text1"        android:background="@color/red"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="文字一" />

不用什么特别的设置。

再加上文本二:

    <TextView        android:id="@+id/text2"        android:padding="20dp"        android:background="@color/blue"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_toRightOf="@+id/text1"        android:layout_alignBaseline="@+id/text1"        android:layout_marginLeft="10dp"        android:text="文字二" />

这里的属性很多了。我们一一看:
1.android:padding=”20dp” ,padding意为“填充”,这个属性定义了当前view的外边界离里面包含的控件的距离,可细分为paddingTop,paddingLeft等。
经过这个属性的设置,蓝色的部分就出来了。

2.android:layout_toRightOf=”@+id/text1”,意为当前控件在目标控件的右边。

注意,这里的右边,代表着文字二可能在文字一的右边的任意地方,包括右上,右下等,所以文字二的位置还是没有确定。

3.因此还需要指定让它们水平对齐,即android:layout_alignBaseline=”@+id/text1”的用处。android:layout_alignBaseline表示基准线对齐。加上后,两控件的位置就定了。
除了这种对齐方式外,还有上边界对齐,左边界对齐等多种对齐方式。

4.android:layout_marginLeft=”10dp”,margin意为边界,android:layout_marginLeft 这个属性的意思是给本控件之外的左边留出指定的距离。
本例子中,如果不加此属性,文字一位于文字二左边,两个挨着。加上后,就是给文字二左边加上了10dp,所以两控件就距离了10dp。

(注意):这样实现的效果,文字一和文字二并不是左右对称的哦,也就是说,中间的10dp并不是位于水平居中的地方。我们实现的只是两个控件整体居中而已。

0 0
原创粉丝点击