Android五大布局与实际应用详解

2019-12-10 18:54:44王旭

这个错误告诉我们在有多个子控件时需要设置布局方向或至少设置一个子控件在该布局方向的大小,我们可以显示设置布局方向或设置某一个子控件的宽度。

除orientation之外还有以下常用属性:

android:gravity:内部控件对齐方式,常用属性值有center、center_vertical、center_horizontal、top、bottom、left、right等。这个属性在布局组件RelativeLayout、TableLayout中也有使用,FrameLayout、AbsoluteLayout则没有这个属性。

center:居中显示,这里并不是表示显示在LinearLayout的中心,当LinearLayout线性方向为垂直方向时,center表示水平居中,但是并不能垂直居中,此时等同于center_horizontal的作用;同样当线性方向为水平方向时,center表示垂直居中,等同于center_vertical。

top、bottom、left、right顾名思义为内部控件居顶、低、左、右布局。

这里要与android:layout_gravity区分开,layout_gravity是用来设置自身相对于父元素的布局。

android:layout_weight:权重,用来分配当前控件在剩余空间的大小。正常情况下,值越大占据高度或宽度越大。例外的情况,在LineayLayout布局中使用这个属性时需要注意: 当水平方向布局且子控件的宽度为fill_parent或match_parent时,值越小占据宽度越大,垂直方向也一样。分析一下这种情况,类似这样的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://www.easck.com/apk/res/android"
  android:orientation="horizontal" android:layout_width="match_parent"
  android:layout_height="match_parent">

  <TextView
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:background="#666666"
    android:text="第一个子控件"
    android:gravity="center"
    android:layout_weight="1"/>
  <TextView
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:background="#EE4000"
    android:text="第二个子控件"
    android:gravity="center"
    android:layout_weight="2"/>

</LinearLayout>