暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

每日一学指Android布局-RelativeLayout

程序员的日记本 2017-11-08
220

前面已经讲过两种布局方式,LinearLayoutTableLayout,大家已经可以看出一些特点,所谓的布局跟大家熟知的布局没啥差别,线性布局就是按水平或者垂直排列,表格布局就是将控件放进一格一格的表格,今天我们要讲的RelativeLayout也是一样的道理。


RelativeLayout:见名思意,相对布局,相对相对,可要有比较才能相对啊,下面通过代码和图片来看看它是怎么相对的。


代码段一:

<RelativeLayout android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_light"
        android:text="测试5555555555555555555555555" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="测试" />
</RelativeLayout>

代码段一效果图:

结论:通过图片可以看出,如果不指定相对的控件,那么相对的元素就是最外层的元素,如果最外层没有,那就是整个屏幕了。


代码段二:

<RelativeLayout android:layout_height="match_parent"
    android:layout_width="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <Button
        android:id="@+id/bt01"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_light"
        android:text="测试5555555555555555555555555" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="25dp"
        android:layout_toRightOf="@+id/bt01"
        android:text="测试" />
</RelativeLayout>

代码段二效果图:

结论:使用toRightOf为控件指定比较的对象,通过margintLeft来控制距离。这样一个简单的相对布局就OK了。


在RelativeLayout布局中,每一个控件都有一系列属性来控制自身的与其相对控件的关系,当然这里不会一一列出来,后面讲解到具体控件的时候在详说:

android:layout_below 在某元素的下方
android:layout_above 在某元素的的上方
android:layout_toLeftOf 在某元素的左边
android:layout_toRightOf 在某元素的右边
android:layout_alignTop 本元素的上边缘和某元素的的上边缘对齐
android:layout_alignLeft 本元素的左边缘和某元素的的左边缘对齐
android:layout_alignBottom 本元素的下边缘和某元素的的下边缘对齐
android:layout_alignRight 本元素的右边缘和某元素的的右边缘对齐
android:layout_centerHrizontal 水平居中
android:layout_centerVertical 垂直居中
android:layout_centerInparent 相对于父元素完全居中
android:layout_alignParentBottom 贴紧父元素的下边缘
android:layout_alignParentLeft 贴紧父元素的左边缘
android:layout_alignParentRight 贴紧父元素的右边缘
android:layout_alignParentTop 贴紧父元素的上边缘
android:layout_alignWithParentIfMissing 如果对应的兄弟元素
找不到的话就以父元素做参照物

OK,上面就是今天要讲的相对布局了,相对布局在App的开发中被经常使用,因为它比TableLayouLinearLayout能够更加的方便控制控件的位置。


如果你觉得文章对你学习有所帮助,或者你想进入到编程的世界,请长按下方图片并关注 人人会编程!

文章转载自程序员的日记本,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论