Android开发之基本控件和四种布局方式详解

2019-12-10 17:55:04于海丽

Android开发,布局

线性布局就先到这儿,因为线性布局方式在Android开发中经常使用到,所以介绍的会多一些。线性布局还有好多其他的用法,等后边博客中用到的时候会详细的介绍。

2.RelativeLayout (相对布局)

上面也说了一下相对布局, 相对布局的本质就是以不变应万变。也就是说相对布局可以根据已经固定的控件来确定其他新加控件的位置。相对布局用的还是蛮多的,接下来我们将通过一个实例来介绍一下RelativeLayout。

首先我们先来看一下我们要实现的效果,实现思路是我们先根据父视图的中心位置来确定center_button的位置,然后再由Center和Parent的位置来确定出其他按钮的位置,这就是相对布局。

Android开发,布局

在相对布局中,你可以设置的属性如下所示,还是蛮多的。在本篇博客中就不做一一介绍了,其用法都差不多。如下图所示:

Android开发,布局

实现上述效果的xml代码如下所示,相对布局使用起来和理解起来还是比较简单的。

<RelativeLayout xmlns:android="http://www.easck.com/apk/res/android"
xmlns:tools="http://www.easck.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.lizelu.userinterfacedemo.MainActivity">
<Button
android:id="@+id/button_center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="center"/>
<Button
android:id="@+id/button_above"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/button_center"
android:layout_centerInParent="true"
android:text="above"/>
<Button
android:id="@+id/button_below"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/button_center"
android:layout_centerInParent="true"
android:text="below"/>
<Button
android:id="@+id/button_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="@+id/button_center"
android:layout_centerVertical="true"
android:text="left"/>
<Button
android:id="@+id/button_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/button_center"
android:layout_centerVertical="true"
android:text="right"/>
</RelativeLayout>