2010-11-06 36 views
8

我正在爲我的Android應用程序製作幾個菜單,並且每次都重複5次標準textview,只更改android:text標記,其他都相同。在Android XML中重複使用TextView代碼

對此有很多屬性,並且對於每個textview複製/粘貼所有這些,感覺效率很低。

有沒有一種方法我只定義一次公共屬性並將它們添加到每個TextView元素?

回答

19

是的,你可以定義一個風格。在您的值res文件夾名稱styles.xml中創建一個文件,並添加如下內容:

<resources> 
    <style name="my_header_text"> 
     <item name="android:textStyle">bold</item> 
     <item name="android:textSize">18sp</item> 
     <item name="android:textColor">@android:color/white</item> 
    </style> 
</resources> 

這定義了樣式。在你的佈局中你可能有這樣一個字段:

<TextView 
    android:id="@+id/my_title" 
    android:layout_height="wrap_content" 
    android:layout_width="wrap_content" 
    style="@style/my_header_text" 
    android:layout_centerVertical="true" 
    android:layout_marginLeft="5dip"/> 

注意樣式聲明引用了上面定義的樣式。樣式幾乎可以包含任何屬性。 Read up on them here

+0

完美答案,謝謝:) – 2010-11-06 10:22:17