之前自己在用Layout的时候用的最多的就是LinearLayout和RelativeLayout了,对其他的其实也只是一知半解。近来也是接触到了更多的Layout在实际中的用途,也算是有了更多的认识。
我现在接触到的比较多的Layout分为几种:LinearLayout,RelativeLayout,FrameLayout,ConstraintLayout。最后再讲一下自己去自定义layout。
LinearLayout
顾名思义,就是一种线性的布局,也是我们最常用到的布局了,一般可以分为水平布局和垂直布局。LinearLayout中有一个我比较喜欢的东西,就是可以通过定义layout_weight来定义布局中每个子view应占的比例大小。这里就不再多做介绍了,做一个简单的布局,效果图及相应代码如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#96ec77" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="2"
android:background="#7cea55" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="#4fec17" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="#5aa8e9" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="#3e9dec" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="3"
android:background="#168bec" />
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="4"
android:background="#1063a7" />
</LinearLayout>
</LinearLayout>
RelativeLayout
从名字也可以看出,这是相对布局。它主要针对的,就是view和view之间的布局关系,以及子view和父view之间的布局关系。大致可以分成以下三种类型:
(1)与父view之间的相对关系,这里用一个图来表示位置关系:
android:layout_centerHrizontal:水平居中
android:layout_centerVertical:垂直居中
android:layout_centerInparent:水平+垂直居中
android:layout_alignParentTop:位于父view的上边缘
android:layout_alignParentBottom 位于父view的下边缘
android:layout_alignParentLeft 位于父view的左边缘
android:layout_alignParentRight 位于父view的右边缘
(2)view与view之