2011年1月24日星期一

使用樣式(style)來簡化在XML中定義按鈕(Button)

有時候,我們會使用許多相同樣式的按鈕; 這種情況下可以使用樣式(style)來簡化在XML中定義按鈕.

使用樣式(style)來簡化在XML中定義按鈕(Button)

創建一個styles.xml檔在/res/values/文件夾中
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="SymbolButtonStyle" parent="android:Widget.Button">
<item name="android:layout_height">wrap_content</item>
<item name="android:layout_width">fill_parent</item>
<item name="android:textSize">25dp</item>
<item name="android:layout_margin">5dp</item>
</style>
</resources>


然後,我們可以在佈局文件中參考它來定義按鈕.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dp"
android:layout_margin="5dp"
android:text="Normal Button"
/>
<Button style="@style/SymbolButtonStyle"
android:text="Button 1" />
<Button style="@style/SymbolButtonStyle"
android:text="Button 2" />
<Button style="@style/SymbolButtonStyle"
android:text="Button 3" />
<Button style="@style/SymbolButtonStyle"
android:text="Button 4" />
<Button style="@style/SymbolButtonStyle"
android:text="Button 5" />
</LinearLayout>




沒有留言:

發佈留言