Android:FrameLayout(帧布局)的理解基本使用

FrameLayout(帧布局)

1、动机

我想在ImageView 上面放置textview 控件,来显示文字,这样我就不需要去画背景了。像是在偷懒。

二、办法:从度娘那里获得一个android 控件 《Framelayout》。

   使用Framelayout 的原因是:可以将控件层叠起来。

2、定义

FrameLayout(帧布局)可以说是六大布局中最为简单的一个布局,这个布局直接在屏幕上开辟出一块空白的区域,当我们往里面添加控件的时候,会默认把他们放到这块区域的左上角,而这种布局方式却没有任何的定位方式,所以它应用的场景并不多;帧布局的大小由控件中最大的子控件决定,如果控件的大小一样大的话,那么同一时刻就只能看到最上面的那个组件!后续添加的控件会覆盖前一个!虽然默认会将控件放置在左上角,但是我们也可以通过layout_gravity属性,指定到其他的位置!

3、android:layout_gravity和android:gravity的使用区别

关于FrameLayout布局的位置问题,首先来看看android:layout_gravity和android:gravity的使用区别。

android:gravity:

这个是针对控件里的元素来说的,用来控制元素在该控件里的显示位置。例如,在一个Button按钮控件中设置如下两个属性,

android:gravity="left"和android:text=“提交”,这时Button上的文字“提交”将会位于Button的左部。

android:layout_gravity:

这个是针对控件本身而言,用来控制该控件在包含该控件的父控件中的位置。同样,当我们在Button按钮控件中设置android:layout_gravity="left"属性时,表示该Button按钮将位于界面的左部。

在这里插入图片描述

4、基本使用

activity_main代码:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is TextView" />
 
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@mipmap/ic_launcher" />
    
</FrameLayout>

在这里插入图片描述

可以看到,文字和图片都是位于布局的左上角。由于ImageView是在TextView之后添加的,因此图片压在了文字的上面。

当然除了这种默认效果之外,我们还可以使用android:layout_gravity属性来指定控件在布局中的对齐方式,这和LinearLayout中的用法是相似的。

修改activity_main.xml中的代码:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
 
    <TextView
        android:id="@+id/tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:text="This is TextView" />
 
    <ImageView
        android:id="@+id/iv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:src="@mipmap/ic_launcher" />
 
</FrameLayout>

在这里插入图片描述

参考

1、https://www.runoob.com/w3cnote/android-tutorial-framelayout.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值