Google Analytics

2013年8月30日 星期五

Android-自定樣式(style)

說明

Andorid專案開發的過程中,會有許多樣式是一再重複使用的,老是一個一個UI元件去設定文字背景的顏色、字型、大小等,是一件毫無效率又容易出錯的事情,與HTML的CSS相似,Andorid也容許使用者預先制定樣式(style),作法是新增或修改styles.xml於res/values/styles.xml下,範例如下:
<?xml version="1.0" encoding="utf-8"?>

<resources>
    <style name="textViewStyle1">
        <item name="android:textColor">#FF0000FF</item>
        <item name="android:background">#FFFF0000</item>
    </style>    
</resources>

若有自訂顏色於res/values/color.xml下時,亦可在styles.xml直接使用,範例如下:
<?xml version="1.0" encoding="utf-8"?>

    <style name="textViewStyle1">
        <item name="android:textColor">@color/blue</item>
        <item name="android:background">@color/red</item>
    </style>    

以下為以TextView設定樣式的範例:
<TextView
        style="@style/textViewStyle1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="藍底紅色" />


沒有留言:

張貼留言