android中的样式和CSS样式作用相似,都是用于为界面元素定义显示风格,它是一个包含一个或者多个view控件属性的集合。如:需要定义字体的颜色和大小。
在CSS中是这样定义的:
<style>
.itcast{
COLOR:#0000CC;
font-size:18px;
}
</style>
可以像这样使用上面的css样式:
<div class="itcast">传智播客</div>
在Android中可以这样定义样式:
在res/values/styles.xml文件中添加以下内容
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name=“itcast”> <!-- 为样式定义一个全局唯一的名字-->
<!-- name属性为样式要用在的View控件持有的属性 -->
<item name="android:textSize">18px</item>
<item name="android:textColor">#0000CC</item>
</style>
</resources>
在layout文件中可以像下面这样使用上面的android样式:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" ....>
<TextView style="@style/itcast"
..... />
</LinearLayout>
实验
values/styles.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="mystyle">
<item name="android:layout_width">fill_parent</item>
<item name="android:textSize">20dip</item>
</style>
<style name="submystyle" parent="mystyle">
<item name="android:layout_width">wrap_content</item>
<item name="android:textColor">#FF0000</item>
<item name="android:gravity">center</item>
<item name="android:padding">10dip</item>
</style>
</resources>
main.xml
<TextView
style="@style/mystyle"
android:layout_height="wrap_content"
android:text="@string/hello" />
<TextView
style="@style/submystyle"
android:layout_height="wrap_content"
android:text="HVGA:480x320" />