android FrameLayout、LinearLayout和RelativeLayout的学习

一、FrameLayout

目的:FrameLayout是一个设计用来存放单个子项的简单容器。它通常被用来堆叠视图,即将多个元素重叠在一起。

布局:子视图堆叠在一起,默认情况下都是放置在左上角,但可以通过android:layout_gravity属性改变子视图的位置。

性能:由于FrameLayout结构简单,所以相对来说比较高效,适合作为其他复杂布局的容器。

应用场景:常用于那些需要重叠显示的场合,如放置一个加载动画在内容上方,或者在图片上覆盖一层半透明的遮罩层等。如下用FrameLayout实现一个按钮在图片上居中的布局

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    
    <ImageView
        android:src="@drawable/image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
        
    <Button
        android:text="Click Me"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"/>
</FrameLayout>
View Code

 

二、LinearLayout

目的:LinearLayout是一种显示子视图为单一行或单一列的布局容器。视图元素根据垂直(vertical)或水平(horizontal)的排列顺序线性排列。

布局:可以通过`android:orientation`属性设置为水平(`horizontal`)或者垂直(`vertical`),比如设置为竖直排列:android:orientation="vertical"。并可以通过`android:layout_weight`属性分配子视图的空间。关于layout_weight的详细说明可以看这一篇博客:https://www.cnblogs.com/czwlinux/p/17002459.html

性能:当管理大量视图时,LinearLayout可能会产生更多的计算工作,因为它需要处理权重和尺寸测量。

应用场景:适用于一系列标准水平或垂直排列的界面元素,比如表格、表单或工具栏。如下用LinearLayout实现一个水平排列的一组按钮

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">
    <Button
        android:text="Button 1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <Button
        android:text="Button 2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
</LinearLayout>
View Code

 

三、RelativeLayout

目的:RelativeLayout 允许子视图相对于彼此或者父容器的某个位置进行定位。你可以指定一个视图位于另一个视图的左侧、右侧、上方或下方,或者相对于父容器的边界对齐等。

布局:在一个 `RelativeLayout` 中,子视图的位置可以通过属性如 `android:layout_toRightOf`、`android:layout_toLeftOf`、`android:layout_above`、`android:layout_below`、`android:layout_alignParentTop` 等来定义。此外,还可以使用 `android:layout_centerInParent`、`android:layout_centerHorizontal`、`android:layout_centerVertical` 等属性将子视图居中。

性能:RelativeLayout`可以非常灵活地布局,但如果层级过深或视图嵌套过多,则可能影响性能,因为布局的测量和放置可能会涉及到多次的遍历和计算。

应用场景:当需要基于其他视图位置关系来定位视图时,RelativeLayout是不错的选择。例如,当你想让一个按钮位于屏幕底部中间,并且另一个视图位于该按钮的上方时,RelativeLayout 就非常有用。

 

四、ConstraintLayout

描述:是一种较新的布局类型,在 Android 开发中被广泛使用,它在灵活性和性能上提供了很好的平衡。

布局:ConstraintLayout和RelativeLayout类似,允许开发者通过使用约束来定义视图之间的关系,而不是使用固定的位置。也有类似LinearLayout的weight的设计

说明:具体会后续单独写一篇专门讲该容器

 

四、其他的布局容器

1、GridLayout

 

posted @ 2024-02-07 17:26  LCAC  阅读(97)  评论(0编辑  收藏  举报