13 Jan 2013


How to change Style of View in Android

Style is a collection of property provides format and look to view or Window.Although style can done only to a particular view or window.However to apply same style to whole application or activity you need to use a theme.
Style in Android is defined in xml file name as style.xml different from the layout xml file.

Style thumbnail

So lets us learn how to apply style to a view.
  • first start eclipse and select new-> file-> android application project.
  • fill the android application project with the following details:
    • Application name-StyleTheme
    • Project name-StyleTheme
    • Package name-style.theme
    • Build SDK-4.1(API-16)
Style Image
  • Now open activity_main.xml file under res-> layout-> activity_main.xml you will see the given code.
  •  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
       xmlns:tools="http://schemas.android.com/tools"  
       android:layout_width="match_parent"  
       android:layout_height="match_parent" >  
       <TextView  
         android:layout_width="wrap_content"  
         android:layout_height="wrap_content"  
         android:layout_centerHorizontal="true"  
         android:layout_centerVertical="true"  
         android:text="@string/hello_world"  
         tools:context=".MainActivity" />  
     </RelativeLayout>  

  • here we have defined properties for the text view individually .Instead of doing this we can use simply apply style for the view by writing these lines.
  •  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
       xmlns:tools="http://schemas.android.com/tools"  
       android:layout_width="match_parent"  
       android:layout_height="match_parent" >  
       <TextView  
        style="@style/myStyle"  
         android:text="@string/hello_world" />  
     </RelativeLayout>  
    

  • Now we need to define the style which we have applied.so open the style.xml under res->layout -> values->style.xml. and we have defined here.
  •  <resources xmlns:android="http://schemas.android.com/apk/res/android">  
       <style name="AppTheme" parent="android:Theme.Light" />  
       <style name="myStyle" parent="@android:style/TextAppearance">  
         <item name="android:layout_width">fill_parent</item>  
         <item name="android:layout_height">wrap_content</item>  
         <item name="android:textColor">#456789</item>  
         <item name="android:textSize">42dp</item>  
          <item name="android:background">#abcdef</item>  
       </style>  
     </resources> 
  • parent attributes in<style> element we have used for inheriting the style attributes.
  • <item> elements is used to redefine the properties according to the requirement of view.
  • for getting more information regarding style attributes visit here.
  • Now run the project you will see the following view.
Style Output

No comments:

Post a Comment

Translate