Android常用布局之AbsoluteLayout(绝对布局)

绝对布局:需要指定子元素的 x,y 精确坐标的布局。

缺点:

绝对布局缺乏灵活性,在没有绝对定位的情况下相比其他类型的布局更难维护,不建议使用。

因为绝对布局,我们开发的应用需要在很多的机型上面进行一个适配,如果使用了这个绝对布局的话,可能你在4寸的手机上是显示正常的,而换成5寸的手机,就可能出现偏移和变形.


目前的Android Studio上使用时候会显示以弃用的标示.

常用属性:

属性 作用
android:layout_width 组件宽度
android:layout_height 组件高度
android:layout_x 设置组件的X坐标
android:layout_y 设置组件的Y坐标

这些属性比较简单,使用起来也比较简单易懂。

实例:

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout 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"
    tools:context=".AbsoluteLayoutActivity">
    <TextView
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:layout_x="110dp"
        android:text="绝对布局"
        android:textSize="50dp"
        android:gravity="center"/>
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_x="50dp"
        android:layout_y="150dp"
        android:src="@drawable/img_2">
    </ImageView>
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_x="50dp"
        android:layout_y="300dp"
        android:src="@drawable/img">
    </ImageView>
    <ImageView
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:layout_x="50dp"
        android:layout_y="450dp"
        android:src="@drawable/zy">
    </ImageView>
    <Button
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_x="250dp"
        android:layout_y="150dp"
        android:background="@drawable/img_2"
        android:text="按钮1">
    </Button>
    <Button
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_x="250dp"
        android:layout_y="300dp"
        android:background="@drawable/img"
        android:text="按钮2">
    </Button>
    <Button
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_x="250dp"
        android:layout_y="450dp"
        android:background="@drawable/zy"
        android:text="按钮3">
    </Button>
    <TextView
        android:layout_width="200dp"
        android:layout_height="100dp"
        android:layout_x="110dp"
        android:layout_y="550dp"
        android:text="通过layout_x和layout_y来调节位置"
        android:textSize="20dp"
        android:textStyle="bold"
        android:gravity="center"/>

</AbsoluteLayout>

效果:

绝对布局是前端布局中最为简单的布局,但灵活性极差,不具有自动适应设备分辨率的能力,就好比在手机上设置的布局,在平板上布局就会全部混乱,所以在日常开发中很少使用绝对布局。

猜你喜欢

转载自blog.csdn.net/qq_62277763/article/details/128671793