FrameLayout的理解基本使用

  • FrameLayout(帧布局)
  • 1、动机
  • 2、定义
  • 3、android:layout_gravity和android:gravity的使用区别
  • 4、基本使用
  • 参考


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按钮将位于界面的左部。

android framelayout上绘图 在 android studio framelayout_xml

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>

android framelayout上绘图 在 android studio framelayout_android_02

可以看到,文字和图片都是位于布局的左上角。由于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>

android framelayout上绘图 在 android studio framelayout_FrameLayout_03

参考

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