Android 系统的布局
前言
在开发过程中,第一个接触的就是布局了,最熟悉的布局文件就是 activity_main.xml 了。今天就来看看布局文件中常见的几大布局。
早期官方给我们提供的布局包括:LinearLayout、FrameLayout、AbsoluteLayout、TableLayout、RelativeLayout。随着 Android 版本的升级,官方也提供了一些新的布局比如说:ConstraintLayout、PercentFrameLayout 和 PercentRelativeLayout 。
这里面常用的有 LinearLayout 、RelativeLayout 和 ConstraintLaout。FrameLayout 经常用于加载 fragment 。下面就来各自介绍下。
LinearLayout 线性布局
放置在 LinearLayout 里面的空间会依次线性排列,可以通过
android:orientation="horizontal | vertical"
来制定是水平排列还是垂直排列,默认值是 horizontal 。
比如(这里的布局外面有一个根布局,所以 xmlns 等信息不需要)
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2" />
</LinearLayout>
效果如图
RelativeLayout 相对布局
该布局可以通过不同控件间的相对位置来进行布局。
比如
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Button1" />
<Button
android:id="@+id/btn_second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn_first"
android:layout_toRightOf="@id/btn_first"
android:text="Button2" />
</RelativeLayout>
效果如图
ConstraintLayout 约束布局
约束布局可以是现在最常用也是最强大的布局了,可以有效减少布局层次,也可以方便完成各种复杂布局。
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="@+id/btn_second"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
app:layout_constraintBottom_toTopOf="@id/btn_first"
app:layout_constraintLeft_toRightOf="@id/btn_first" />
</android.support.constraint.ConstraintLayout>
效果如图
当然这里面的用法还有很多,暂时就不详细介绍了。推荐两篇文章
https://blog.****.net/lmj623565791/article/details/78011599
https://juejin.im/post/5c0bd6b05188257c3045dc50
FrameLayout 帧布局
该布局很简单,里面所有的控件都会放置在左上角。
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@mipmap/ic_launcher" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello I am TextView!"
android:textColor="@android:color/holo_red_dark" />
</FrameLayout>
效果如图
总结
这里只是简单的罗列下常用布局的基本功能,每个布局又都有其各自独特的功能和效果,来完成页面的绘制。