Colors Arrays and Dimensions Resources

| |
Android provides three other types of resources that can be defined as XML files in the res/values folder. These resources can be Colors, Arrays and Dimensions.

Color Resources:
You can define XML files that contain definitions for colors that can be used in your application.


Colors in Android are hexadecimal RGB values, also optionally specifying an alpha channel (transparency).

You have your choice of single-character hex values or double-character hex values, leaving

you with four styles:

  • #RGB (Red: #F00).
  • #ARGB (Red with Alpha 5: #5F00).
  • #RRGGBB (Red : #FF0000).
  • #AARRGGBB (Red with Alpha 50: 50FF0000 #).
You define colors in the xml file as follows:

<color name="Red">#FF0000</color>
You can use it from code behind as this:
TextView txtColor=(TextView)findViewById(R.id.txtColor);
txtColor.setTextColor(this.getResources().getColor(R.color.Red));

or from the layout as this:



Dimensions Resources:
You can define Dimension resources to use them with your widgets to define padding, width or height.


The dimension resources can be defined in the following units:

  • Pixels: (px).
  • Inches: (in).
  • Millimeters: (mm).
  • Points: (pt).
  • Density: (dp) density-independent pixels based on 160 dpi (dot per inch).
  •  Scale: (sp) Scale-independent pixels (dimensions that allow for user sizing; helpful for use in
    fonts).
To define dimension resources in xml files you can write it like this:

<dimen name="PixelDim">10px</dimen>
<dimen name="PointsDim">10pt</dimen>
<dimen name="InchesDim">0.2in</dimen>
<dimen name="MilliDim">5mm</dimen>
<dimen name="DensityDim">20dp</dimen>
<dimen name="ScaleDim">20sp</dimen>


And you can use them from the xml layout definition like this



or from code like this:
TextView txtdp=(TextView)findViewById(R.id.txtdp);
txtdp.setTextSize(this.getResources().getDimension(R.dimen.DensityDim));


Array Resources:
Array resources allow you to define custom string arrays that hold values you can use in your application such as a countries list or a list of names.


An Array resource is defined using string-array element while items are defined using item element.

<string-array name="countries">
<item>USA</item>
<item>UK</item>
<item>Canada</item>
</string-array>

and you can use them from code like this:
String [] Countries=this.getResources().getStringArray(R.array.countries);
you can define more than one string-array in the same file


that was all about color, dimensions and arrays in android

Download sample application from here

Related Posts by Categories

0 comments:

Post a Comment