Styles



Build visually compelling Apps

While working with android you must have felt the importance as well as difficulties while styling your app.This article will help you understand the basics and utility of Styles in android.

Style in android are the properties pertaining to look and format of a view or a window.

A theme is a style applied to an entire Activity or application.

Resources

All the app resources such as static content like layouts, strings etc are placed in res/ directory. res/values/ has XML files that contain simple values, such as strings, styles, colors etc.

XML resource files in other res/ subdirectories define a single resource based on the XML filename whereas files in the values/ directory describe multiple resources. For a file in this directory, each child of the <resources> element defines a single resource. For example, a <string> element creates a R.string resource and a <color> element creates a R.color resource.

All these resources are compiled and assigned an interger value in R.java file located at project/build/generated/source/r/debug/package/R.java or simply use ctrl+ N and type R.

Alternative Resources

You app runs on devices with different configuration.For example, to optimize the app for different screen sizes and densities you must provide alternative resources.Here is the way to do that:

Create a new directory in res/ named in the form

 <resources_name>-<config_qualifier>
  • <resources_name> is the directory name of the corresponding default resources.

  • <qualifier> is a name that specifies an individual configuration for which these resources are to be used.

For example: drawable/ and drawable-hdpi/ .The resource files must be named exactly the same as the default resource files.

Accessing Resources

So how to access these resources in your project? Let’s have a look at this.

When the application is compiled, aapt(Android Asset Packaging Tool) generates the R class, which contains resource IDs for all the resources in project’s res/ directory.

For each type of resource, there is an R subclass (for example, R.drawable for all drawable resources), and for each resource of that type, there is a static integer (for example, R.drawable.icon). This integer is the resource ID.

A resource ID is always composed of:

  • The resource type
  • The resource name

There are two ways to access a resource:

  1. Reference a resource in code:

    [<package_name>.]R.<resource_type>.<resource_name>

    For example:

         // Load a background for the current screen from a drawable resource
    
         getWindow().setBackgroundDrawableResource(R.drawable.background_image) ;
    

    drawable is the resource type and background_image is the resource name

  2. In xml

    @[<package_name>:]<resource_type>/<resource_name>

    For example:

     <Button
      android:layout_width=”fill_parent”
      android:layout_height=”wrap_content”
      android:text=”@string/submit” />
    

    <package_name> is the name of the package in which the resource is located (not required when referencing resources from your own package). <resource_type> is the R subclass for the resource type. <resource_name> is either the resource filename without the extension or the android:name attribute value in the XML element (for simple values). To reference a system resource, one would need to include the package name. For example:

     android:textColor=”@android:color/secondary_text_dark”
    

Referencing style attributes

A style attribute resource allows you to reference the value of an attribute in the currently-applied theme.

Syntax:

?[<package_name>:][<resource_type>/]<resource_name>

For Example:

   <EditText id="text"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="?android:textColorSecondary"
        android:text="@string/hello_world" />

Because the system resource tool knows that an attribute resource is expected in this context, we do not need to explicitly state the type (which would be ?android:attr/textColorSecondary) — we can exclude the attr type.

Accessing Platform Resources

Android contains a number of standard resources, such as styles, themes, and layouts.You need to add android package name to access these resources. For example:

setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myarray));

simple_list_item_1 is a layout resource defined by the platform for items in a ListView.

Styles

Now we are all set to define styles.Here we go.

To create a set of styles, save an XML file in the res/values/ directory of your project. The name of the XML file is arbitrary, but it must use the .xml extension and be saved in the res/values/ folder.

The root node of the XML file must be <resources>.

For each style you want to create, add a <style> element to the file with a name that uniquely identifies the style (this attribute is required). Then add an <item> element for each property of that style, with a name that declares the style property and a value to go with it (this attribute is required). The value for the <item> can be a keyword string, a hex color, a reference to another resource type, or other value depending on the style property. For example:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyFontStyle" parent="@android:style/TextAppearance.Medium">
        <item name="android:layout_width">fill_parent</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#00FF00</item>
        <item name="android:typeface">monospace</item>
    </style>
</resources>

Each child of the <resources> element is converted into an application resource object at compile-time, which can be referenced by the value in the <style> element’s name attribute. This example style can be referenced from an XML layout as @style/MyFontStyle.

The parent attribute in the <style> element is optional and specifies the resource ID of another style from which this style should inherit properties.

Inheritance

The parent attribute in the <style> element lets you specify a style from which your style should inherit properties.

  1. Inherit properties from an existing style

     <style name="GreenText" parent="@android:style/TextAppearance">
             <item name="android:textColor">#00FF00</item>
         </style>
    
  2. Inherit from styles that you’ve created yourself

     <style name="MyFontStyle.Red">
             <item name="android:textColor">#FF0000</item>
         </style>
    

You can continue inheriting like this as many times as you’d like, by chaining names with periods.This technique for inheritance by chaining together names only works for styles defined by your own resources.

Style Properties

For a reference of all available style properties, see the R.attr reference. Keep in mind that all View objects don’t accept all the same style attributes, so you should normally refer to the specific View class for supported style properties.

Apply a theme

You can find this attribute in your AndroidManifest.xml file

 <application android:theme="@style/CustomTheme">

If you want a theme applied to just one Activity in your application, then add the android:theme attribute to the<activity> tag instead.

As of Android 5.0 (API 21) you can also assign the android:theme for a view. This allows to change the theme for this element and its child elements.

Select a theme based on platform version

To have a theme when the application is running on Android 3.0 (API Level 11) or higher, you can place an alternative declaration for the theme in an XML file in res/values-v11.Similarly for API Level 21 and above use res/values-v21.We’ll shortly see its great utility in maintaining compatibility.

A list of the standard attributes that you can use in themes can be found at R.styleable.Theme.

Using Platform Styles and Themes

The Android platform provides a large collection of styles and themes that you can use in your applications. You can find a reference of all available styles in the R.style class.

For a better reference to the Android styles and themes, see the following source code:

  • Android Styles (styles.xml)
  • Android Themes (themes.xml)

For a reference of available style attributes that you can use to define a style or theme (e.g., “windowBackground” or “textAppearance”), see R.attr or the respective View class for which you are creating a style.

Styling Button

You can style your button such that it will change appearance depending on its current state.

Custom background To achieve this your background should be a state list resource.

You can define the state list in an XML file that defines three different images or colors to use for the different button states.

Create a new XML file in the res/drawable/ directory (name it something like button_custom.xml). Insert the following XML:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/button_pressed"
          android:state_pressed="true" />
    <item android:drawable="@drawable/button_focused"
          android:state_focused="true" />
    <item android:drawable="@drawable/button_default" />
</selector>

The order of the <item> elements is important.

Now simply apply the drawable XML file as the button background:

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/bSend"
    android:onClick="sendMessage"
    android:background="@drawable/button_custom"  />

Maintaining Compatibility

New themes are introduced which provides new features for apps running on higher API levels.So that means while making use of those features your app won’t run on older versions.Well that is not the case and android provides a nice workaround.

  1. For example: You want to use material theme for API level 21 and above.Create a file themes.xml and put it under values folder.This will be used as default theme for lower API levels.

    res/values/themes.xml:

     <resources>
         <style name="MyTheme" parent="@android:style/Theme">
             <!-- Any customizations for your app running on pre-5.0 devices here -->
         </style>
     </resources>
    

    And make another file with similar name and put it under values-v21 folder.

    res/values-v21/themes.xml:

     <resources>
         <style name="MyTheme" parent="@android:style/Theme.Material">
             <!-- Any customizations for your app running on devices with Theme.Material here -->
         </style>
     </resources>
    

    Finally, in AndroidManifest.xml:

         <application android:name="MyApplication"
                 android:label="@string/application_label"
                 android:icon="@drawable/app_icon"
                 android:hardwareAccelerated="true"
                 android:theme="@style/MyTheme">
    
  2. Use Support Library

    The Android Support Library package is a set of code libraries that provide backward-compatible versions of Android framework APIs as well as features that are only available through the library APIs. Each Support Library is backward-compatible to a specific Android API level.




We new friends!