Use of styles allows you to define reusable visual settings to help maintain a consistent look-and-feel to your app.
The simple example below shows how to create a style for titles, which will be larger text, and warnings which will be red. Each style must have a name and can then list multiple properties:
values/styles.xml
values/styles.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <style name="myTitle"> <item name="android:textSize">16sp</item> </style> <style name="myWarning" parent="@style/myTitle"> <item name="android:textStyle">bold</item> <item name="android:textColor">@colors/myRed</item> </style> </resources>
A few things to note here, firstly that you can put any styling name into the item tag that you would use within your layout definitions. Also note that myWarnings has its parent set as myTitle and so inherits the 16sp text size defined there. Finally, the textColor value could be a standard hex colour (i.e. #FF0000) but it is good practice to put colours into a separate resource so that one you only need to update one location if you want to change it:
values/colors.xml
<?xml version="1.0" encoding="utf-8"?> <resources> <color name="myRed">#FF0000</color> </resources>
Now it is simply the case of applying the style within your layouts:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="My styled text view"
style="@styles/myWarning" />
</LinearLayout>
Note that the style attribute is not prefixed by the android tag.
0 comments:
Post a Comment