Android布局FrameLayout的使用

来源:互联网 发布:自助域名绑定如何实现 编辑:程序博客网 时间:2024/06/04 15:51

序:本文介绍FrameLayout两点:1.FrameLayout是什么 2.FrameLayout如何设置其内子视图(例如ImageView)的位置。

1. 什么是FrameLayout布局?

    FrameLayout布局是最简单的布局方式,所有添加到这个布局中的视图都是以层叠的方式显示。第一个添加到布局中视图显示在最底层,最后一个被放在最顶层。上一层的视图会覆盖下一层的视图,因此该布局类似于堆栈布局。注意点:a.默认对其方式是左上角对其。b.若要设置子视图的位置,要设置layout_gravity属性值。

2.FrameLayout如何设置其子视图(例如ImageView)的位置?

    通过layout_gravity设定值,再配合layout_marginTop,layout_marginLeft来设置位置。

    举例,下面程序结果截图中,有4幅图:第一层图天空大背景,第二层图是鸟图,第三层图是观音菩萨图,第四层图是汽车图。若不设置ImageView的位置,则此四幅图都将默显示在左上角,并且第一层图在最下面,第四层图在最上面。要实现图中四幅图的位置效果,则分别对应以下设置:

    a. 第一层天空背景图 : layout_gravity="center"

    b. 第二层鸟图 : layout_gravity = "center"  layout_marginTop="-70dp"  (注意:此处是负数,因为  layout_gravity = "center" 表示水平和垂直方向上居中,基准线为视图水平和垂直方向的中点,因为鸟在基准线的上方向(负方向),所以为负数)

    c. 第三层观音菩萨图 :layout_gravity="top" layout_marginTop="20dp" layout_marginLeft="20dp'  (注意:layout_gravity="top" 表示垂直方向顶端对齐,而水平方向是默认左对齐)

    d. 第四层汽车图 : layout_gravity="center" layout_marginTop="40dp" (对应第二层鸟图的分析,就很容易理解,汽车在基准线下方向(正方向),所以为负数。并且注意:此处的基准线不是屏幕的最上方,而是水平和垂直方向各自的中心线)

以上的分析,请参考下图实际程序运行结果图和视图代码。

---------------------------------------------------------------------------------------------------------------------------------------------

程序运行结果图:


页面视图代码:/res/layout/activity_main.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="fill_parent"android:layout_height="fill_parent" > <ImageView android:layout_width="fill_parent"android:layout_height="wrap_content"android:layout_gravity="center"android:background="@drawable/sky2"/> <ImageView android:layout_width="40dp"android:layout_height="26dp"android:layout_gravity="center"android:background="@drawable/bird"android:layout_marginTop="-70dp"/> <ImageView android:layout_width="75dp"android:layout_height="98dp"android:layout_gravity="top"android:background="@drawable/guanyinpusa"android:layout_marginTop="20dp"android:layout_marginLeft="20dp"/> <ImageView android:layout_width="80dp"android:layout_height="50dp"android:layout_gravity="center"android:background="@drawable/car"android:layout_marginTop="40dp"/> </FrameLayout>


      


1 0
原创粉丝点击