安卓开发入门教程-常用布局_FrameLayout

2,614 阅读2分钟

什么是FrameLayout

FrameLayout又称帧布局,开发中很少使用,因其定位方式过于简单,所有控件都默认定位左上角.也支持将子控件显示在父控件的上下左右及正中间.

基础样例

1. 默认定位样例

效果图

代码

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是文本显示控件TextView" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="我是按钮" />
</FrameLayout>

2. 相对父控件定位

效果图

代码

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="start"
        android:text="左上" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end"
        android:text="右上" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="中心按钮" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:text="左下" />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:text="右下" />
</FrameLayout>

代码说明:

  1. android:layout_centerInParent,设置是否在父控件中居中(横向和纵向).
  2. android:layout_alignParentStart,设置是否和父控件左对齐.
  3. android:layout_alignParentEnd,设置是否和父控件右对齐.
  4. android:layout_alignParentTop,设置是否和父控件上对齐(因为默认就是上对齐的,所以就不用设置了).
  5. android:layout_alignParentBottom,设置是否和父控件下对齐.

基础样例完整源代码

gitee.com/hspbc/Frame…

常用属性说明

属性名用途
android:layout_width设置控件宽度,可设置为:match_parent(和父控件一样),wrap_content(按照内容自动伸缩),设置固定值(如200dp)
android:layout_height设置控件高度,可设置为:match_parent(和父控件一样),wrap_content(按照内容自动伸缩),设置固定值(如200dp)
android:background设置背景,可以是色值(如#FF0000)或图片等
android:visibility可选值: visible(显示), invisible(隐藏,但是仍占据UI空间),gone(隐藏,且不占UI空间)
android:layout_gravity当前控件在父控件中的位置,可选值:start(居左),end(居右),center(居中),top(居上),bottom(居下),属性可组合,用竖线分隔.

更多属性及实际效果,可以在开发工具里自行体验.

关于我

厦门大学计算机专业|华为八年高级工程师
十年软件开发经验,5年编程培训教学经验
目前从事编程教学,软件开发指导,软件类毕业设计指导。
所有编程资料及开源项目见juejin.cn/post/700279…