Android 样式布局

知识就是力量,时间就是生命。这篇文章主要讲述Android 样式布局相关的知识,希望能为你提供帮助。
一、样式布局
【Android 样式布局】首先,先看下面这段样式布局代码,这里称在xml控件上添加属性为内联(仅限于本篇博文这样称呼):

< Button android:id="@+id/crime_date" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp"/> < CheckBox android:id="@+id/crime_solved" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:text="@string/solved_btn"/> < Button android:id="@+id/choose_btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:text="@string/choose_name"/> < Button android:id="@+id/contact_btn" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginLeft="16dp" android:layout_marginRight="16dp" android:text="@string/contacter_name"/>

在上面这段XML布局代码,可以看出,各个按钮的样式完全一样,添加某个属性给控件就有多次。假如,有更多的控件使用相同的而已,要做N次重复的工作。Android提供了各种样式UI,可用于解决重复性的工作。样式资源类似于CSS样式。样式也可以具有层级结构:子样式拥有父式样同样的属性及属性值,可以覆盖它们,也可以添加新的属性。
类似字符资源,样式定义在XML文件的< Resources> 酬标签内,并存放在res/values目录中。另外,资源文件取什么名并不重要,但根据约定,样式通常定义在style.xml文件中。在Android项目中,已经默认创建了这个文件。
Style.xml文件:
1 < resources> 2< style name="Crime_btn_style1"> 3< item name="android:layout_width"> wrap_content< /item> 4< item name="android:layout_height"> wrap_content< /item> 5< item name="android:layout_marginLeft"> 16dp< /item> 6< item name="android:layout_marginRight"> 16dp< /item> 7< /style> 8 < /resources>

layout/fragment_crime.xml文件,将控件的属性以style样式名引入的方式在外联(仅限于本篇博文这样称呼):
1 < Button 2android:id="@+id/crime_date" 3style="@style/Crime_btn_style1"/> 4 5 < CheckBox 6android:id="@+id/crime_solved" 7android:text="@string/solved_btn" 8style="@style/Crime_btn_style1"/> 9 10 < Button 11android:id="@+id/choose_btn" 12android:text="@string/choose_name" 13style="@style/Crime_btn_style1"/> 14 15 < Button 16android:id="@+id/contact_btn" 17android:text="@string/contacter_name" 18style="@style/Crime_btn_style1"/>

  PS:需要注意的是,在内联属性与外联属性冲突时,以内联属性为准,也可以说,内联属性优于外联属性方式。
二、include与merge
include使用资源ID引入而已文件。
layout/button_row.xml
1 < TableRow 2 xmlns:android="http:/schemas.android.com/apk/res/android"> 3< Button style="@style/Crime_btn_style1"> 4< Button style="@style/Crime_btn_style1"> 5< Button style="@style/Crime_btn_style1"> 6 < /TableRow>

layout/fragment_crime.xml
1 < include 2android:layout_weight="1" 3layout="@layout/button_row" /> 4 < include 5android:layout_weight="1" 6layout="@layout/button_row" /> 7 < include 8android:layout_weight="1" 9layout="@layout/button_row" />

以上代码表明,include将引入资源ID为button_row文件内容。
PS:include标签只能引用layout布局文件,也就是只能引用layout目录下的布局文件。

    推荐阅读