Android 中的 FrameLayout 与 AbsoluteLayout 的区别
简介
框架布局和绝对布局是开发 Android 应用程序时使用的两种不同布局。框架布局用于在堆叠布局中显示单个子视图,其中 UI 元素以堆叠的方式相互叠加。它类似于用于显示多个 UI 元素的相对布局。而绝对布局用于指定元素在屏幕上的精确位置。绝对布局在适应不同屏幕尺寸方面灵活性较差。
Android 中的框架布局是什么?
框架布局是一个视图组类,用于指定以堆叠格式排列的元素在屏幕上的精确位置。这是一个相对简单的布局,可用于在彼此顶部显示多个 UI 元素,最后添加的元素显示在顶部。
如何在 Android 应用中显示框架布局
在 Android 布局文件中添加 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">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:src="@drawable/background_image" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello, World!"
android:textSize="24sp"
android:layout_gravity="center" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me"
android:layout_gravity="bottom|right"
android:layout_margin="16dp" />
</FrameLayout>
说明:在上面的代码中,我们创建了一个框架布局作为根布局。在这个布局中,我们创建了一个图像视图、一个文本视图和一个按钮。
框架布局的属性如下
属性 |
描述 |
|---|---|
android:id |
用于唯一标识组件。 |
android:foreground |
用于指定 RGB 中的前景色值。 |
android:foregroundGravity |
用于指定 RGB 值中的前景色。 |
android:measureAllChildren |
用于测量所有可见的子元素。 |
Android 中的绝对布局是什么?
绝对布局用于使用屏幕的 (x,y) 坐标指定元素的精确位置。由于绝对布局已被弃用,因此不推荐在现代 Android 应用程序开发中使用。
绝对布局相关问题
响应性不足 − 绝对布局不提供自适应不同屏幕尺寸、方向和分辨率的响应式布局。由于 UI 元素的位置以 (x,y) 坐标表示,因此是固定的。如果屏幕尺寸增加,该元素的位置可能会受到影响。
不支持无障碍功能 − 绝对布局不支持屏幕阅读器等无障碍功能,因为该布局无法提供有关 UI 元素之间关系的有意义的信息,因此残障用户的可访问性较差。
维护困难 − 由于 UI 元素的位置是使用坐标指定的,因此随着屏幕尺寸的变化,维护起来非常困难。
如何在 Android 应用中显示表格布局
Add XML in your Android Layout file
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- on below line creating a table row -->
<TableRow>
<!-- creating a text view on below line -->
<TextView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:text="Hello" />
<!-- creating image view on below line -->
<ImageView
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:src="@drawable/ic_android" />
</TableRow>
</TableLayout>
说明:在上面的代码中,我们创建了一个表格布局作为根布局。在这个表格布局中,我们创建了一个用于显示各个行的表格行。在这个表格行中,我们显示了一个文本视图和一个图像视图。
表格布局的属性如下
属性 |
描述 |
|---|---|
android:id |
用于唯一标识绝对布局。 |
android:layout_x |
指定表格的 X 坐标视图。 |
android:layout_y |
它指定视图的 Y 坐标。 |
框架布局 VS 绝对布局
框架布局 |
绝对布局 |
|---|---|
框架布局允许您以堆叠方式显示 UI 元素。其中最后添加的元素将显示在顶部。 |
绝对布局允许您通过使用 (x,y) 坐标提供元素的精确位置来显示 UI 元素。 |
框架布局在响应速度和对不同屏幕尺寸和方向的适应性方面提供了更大的灵活性。 |
绝对布局不提供任何灵活性,因为我们使用坐标指定 UI 组件。 |
在框架布局中,UI 元素相对于父布局的边缘或其内的其他 UI 元素进行定位。 |
使用绝对布局创建响应式 UI 非常困难。 |
框架布局是推荐的叠加 UI 元素的方法。用于以堆栈格式显示 UI 元素。 |
绝对布局已被弃用,不建议在现代 Android 应用开发中使用。 |
结论
总而言之,框架布局是一种更灵活且推荐的 Android 应用开发 UI 元素定位方法。而绝对布局由于其局限性和响应性问题已被弃用,不建议使用。建议根据您的具体 UI 设计需求使用其他布局类型,例如约束布局、线性布局或相对布局。

