SJ46 初識ViewGroup,父與子

ViewGroup


ViewGroup

其他View的容器,作為父布局
View作為子視圖

LinearLayout 線性布局
子視圖排成垂直的一排,也可以水平排列

RelativeLayout 相對布局
子視圖與父布局相對排列,也可以子視圖之間相對排列

<LinearLayout   //父布局,將子視圖放入雙標簽內(nèi)
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView   //子視圖
        android:text="Guest List"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    
    <TextView   //子視圖
        android:text="Kunal"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    
</LinearLayout>

父布局也有屬性和值,如

xmlns:android="http://schemas.android.com/apk/res/android"

XML 命名空間說明,用命名空間來指定Android屬性,這就是為什么屬性前都有個(Android:)(即表示這些是Android屬性),實際上是特指給Android的URL速記屬性。為了避免名字上的沖突(即屬性被設為同一個名字,卻又不同的行為)得在這里加前綴。

android:orientation="vertical"   //horizontal
android:layout_width="wrap_content"
android:layou_height="wrap_content"

視圖大小

android:layout_width="match_parent"
android:layout_height="match_parent"
//與父布局的寬高等同

對于有下劃線的屬性 如 android:layout_width,這些是由父布局處理,決定視圖大小、位置參數(shù)

對于其他屬性 如 android:textSize,這些是由子視圖風格化自己視圖來處理

在線性布局中均勻分布

android:layout_height="0dp"
android:layout_weight="1" //布局權(quán)重,與其他子視圖占整個屏幕比例

先將該視圖的height設置為0dp,然后排列其他子視圖,再根據(jù)剩余空間按權(quán)重分配高度給該視圖

vertical LinearLayout 設置layout_htight="0dp"
horizontal LinearLayout設置layout_width="0dp"

RelativeLayout

對于單獨一個子視圖來說

android:layout_alignPatentTop="true"http://與父視圖的上邊緣對齊
android:layout_alignPatentBotton="true"http://與父視圖的下邊緣對齊
android:layout_alignPatentRight="true"http://與父視圖的右邊緣對齊
android:layout_alignPatentLeft="true"http://與父視圖的左邊緣對齊
android:layout_horizontal="true"http://與父視圖垂直居中
android:layout_centerVertical="true"http://與父視圖水平居中

這些屬性都可以搭配使用,android:layout_alignPatentLeft默認為true,其他屬性默認為false

對于子視圖互相來說

<TextView
    android:id="@+id/text_view"http://新添加一個id為text_a的文本視圖
    …… 
    />
<ImageView
    android:layout_toLeftOf=“@id/text_view”//圖片在文本視圖的左邊
    ……
    />

@+id/text 向資源文件夾中添加id為text的引用(注引用名不能有空格)

@id/text 引用id為text的TextView

android:layout_toRightOf//在其右側(cè)
android:layout_above//在其頂部
android:layout_below//在其底部

padding

android:padding="8dp"
OR
android:paddingTop="8dp"
android:paddingBotton="8dp"
android:paddingLeft="8dp"
android:paddingRight="8dp"
padding.png

視圖內(nèi)容到視圖邊緣的距離,由視圖自己處理

margin

android:margin="8dp"
OR
android:marginTop="8dp"
android:marginBotton="8dp"
android:marginLeft="8dp"
android:marginRight="8dp"
margin.png

視圖邊緣與父視圖或其他子視圖的距離,由父視圖ViewGroup處理

Material desdign 建議padding或margin的距離為8dp的倍數(shù)

總結(jié)

  1. 模塊化,作為獨立的類和布局優(yōu)先構(gòu)建
  2. 復用代碼
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容