Tuesday, 3 May 2016

Handling Application Resources


Introducing Resources :
ü  Resources play a key role in Android Architecture. A resource in Android is a file (like a music file)or a value(like the title of a dialog box) that is bound to an executable application. These files and values are bound to the executable code so that we can change them without need of recompiling the application.           
ü  Examples of resources include strings, colors, and bitmaps.
ü We can create and store our resource files under the appropriate subdirectory “res/” directory in our project. Android has a resource compiler (AAPT-Android Asset Packaging Tool) that compiles resources according to which subfolder they are in, and the format of the file.
Why We need Resources :  
ü  The resources are bound to the application so that we can change them without needing to change the source code or recompile the application.
ü  The Android Generates an ID for each resource file so we can access them directly and easily in our java code. All the resources IDs are added to the R.Java file.
ü  Using resources is very useful in Localization and Internationalization of the application while develop multilingual applications.
ü Resources includes not just the labels but it can include alignment, directions images or any kind of files.
Resources class :
ü  Class for accessing an application's resources, defined in android.content.res.* package.
ü The Android resource system refers all non-code assets associated with an application, like images, audio, video ..etc. We can use this class to access our application's resources. We can generally acquire the Resources instance associated with our application with getResources().
Method :
AssetManager getAssets();
boolean getBoolean(int id);
int getColor(int id);
float getDimension(int id);
int[] getIntArray(int id);
int getInteger(int id);
Movie getMovie(int id);
String getString(int id);
String[] getStringArray(int id);
XMLResourceParser getXML(int id);
InputStream openRawResource(int id);
..etc




Configuration Class :
ü  This class describes all device configuration information like as input modes, screen size and screen orientation.
ü  We can get this object from Resources, using getConfiguration(),from an activity, we can get it by chaining the request with getResources():

    Resources res=getResources();
    Configuration config = res.getConfiguration();
            Fields :
1.      int ORIENTATION_LANDSCAPE
2.      int ORIENTATION_PORTRAIT
3.      int ORIENTATION_SQUARE
.etc
Example : Get Current Screen Orientation in ANDROID
The following method does the required functionality.
public int getScreenOrientation() {
//orientationis.
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
   // The following message is only displayed once.
    return 1; // Portrait Mode
}else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
   // The following message is only displayed once.
    return 2;   // Landscape mode
}
return 0;
}
Types of Resources
  • Strings, colors, arrays, dimensions. Defined in res/values directory. Using them is very useful in Localization and Internationalization.
  • Images put in res/drawable directory.  We can put all the images or icons we need in our application.
  • Animations, defined in res/anim directory. We can define animations.
  • XML, defined in res/xml directory for xml files containing our custom data.
  • Layout resources, defined in res/layout for declaring the views that construct the user interface of the activities.
Resource Type
Location
Description
Colors
/res/values/any-file
Represents Color identifiers pointing to color codes. Can access using R.color.*
The XML Node in the file is /resources/<color>
Strings
/res/values/any-file
Represents String resources. Can access using R.string.*. The XML Node in the file is /resources/<string>
String arrays
/res/values/any-file
Represents a resource that is an array of strings. Can access using R.array.*. The XML Node in the file is /resources/<string-array>
Dimensions
/res/values/any-file
Represents dimensions or sizes of various elements or views in Android. Supports pixels, inches, millimeter, density independent pixels, and scale independent pixels. Can access using R.dimen.*. The XML Node in the file is /resources/<dimen>
Images
/res/drawable/multiple-files
Represents image resources. Supports images include .jpg, .gif, .png etc. Can access usingChennai H O R.drawable.*
Arbitrary XML files
/res/xml/*.xml
Android allows arbitrary XML files are resources. These files will be compiled by AAPT compiler. Can access using R.xml.*
Arbitrary raw resources
/res/raw/*.*
Allows arbitrary non compiled binary or text files under this directory like .txt, audio or video files. Can access R.raw.*

Working with string resources
            /res/values/string.xml
1.      Single Value String values:
<resource>
            <string name=”name”> Mallikarjun Rao </string>
            <string name=”shortname”>MKRao </string>
</resources>
                        Accessing String values in layout files (for Ex in main.xml)
<TextView …..
            android:text=”@string/name”/>
</TextView>
2.      String Array Values:
<resource>
            <string-array name=”test_array”>
                        <item>one</item>
                        <item>two</item>
                        …etc
            </string-array>
</resources>
      Accessing from java code
Resources res=this.getResources();
String strings[]=res.getSringArray(R.array.test_array);
for(….){ …..}
Working with Boolean resources
            <bool> is the tag used to Boolean values in xml file, values may be true/false
            res/values/bools.xml
<?xml version="1.0" encoding="utf-8"?>

<resources>

    <bool name="screen_small">true</bool>

    <bool name="adjust_view_bounds">true</bool>

</resources>
           
Accessing from layout xml file (for Ex : main.xml)
<ImageView…… android:adjustViewBounds="@bool/adjust_view_bounds"/>
     Accessing from Java Code :
Resources res = getResources();

boolean screenIsSmall = res.getBoolean(R.bool.screen_small);
            
Working with integer resources
Used to define Integer constants in xml file we can define in two ways, are
i)                    Single Value Integers :
XML file saved at res/values/integers.xml:
<?xml version="1.0" encoding="utf-8"?>

<resources>

    <integer name="max_speed">75</dimen>

    <integer name="min_speed">5</dimen>

</resources>
            Accessing from java code :
     Resources res = getResources();

  int maxSpeed = res.getInteger(R.integer.max_speed);
ii)                  Integer Array :
XML file saved at res/values/integers.xml:
<?xml version="1.0" encoding="utf-8"?>

<resources>

    <integer-array name="bits">

        <item>4</item>

        <item>8</item>

        <item>16</item>

        <item>32</item>

    </integer-array>

</resources>
            Accessing from java code :
     Resources res = getResources();

  int[] bits = res.getIntArray(R.array.bits);

Working with color resources
            res/values/color.xml
<resources>
            <color name=”red”>#f00</color>
            <color name=”green”>#f0f0</color>
            …etc
</resources>
            Applying color to textview in layout file (for Ex main.xml)
<TextView ….
            android:textColor=”@color/red”>
</TextView>
            Getting color in java code
int color=currentactivity.getResources.getColor(R.color.red);


Working with Dimension Resources :
            Pixels, inches, and points are all examples of dimensions that can play a part in XML layouts or Java Code.
            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 font sizes, image sizes..etc).
      res/values/dimens.xml
<resources>

    <dimen name="icon_width">55dp</dimen>

    <dimen name="icon_height">55dp</dimen>
            <dimen name=”medium_size”>100sp</dimen>
            ..etc
   </resources>
Accessing from layout xml file(for Ex main.xml file)
<TextView ……android:textSize=”@dimen/medium_size”/>
            Getting dimension in java code :
txtdp.setTextSize(this.getResources().getDimension(R.dimen.medium_size));
Working with image resources
ü  Android generates resource IDs for image files placed in the /res/drawable subdirectory. The supported image types include .gif, .jpg, and .png. Each image file in this directory generates a unique ID from its base file name. If the image file name is sample_image.jpg, for example, then the resource ID generated will be R.drawable.sample_image.
ü  We have four types of drawable folders:
·         Low density screens (ldpi): 36x36px, 120dpi
·         Medium density screens (mdpi): 48x48px, 160dpi
·         High density screens (hdpi): 72x72px, 240dpi
·         Extra high density screens (xdpi): 96x96px, 320dpi
ü  These folders are used to put our images in to adapt to different screen sizes. For example we may create two files of the same image, one for high density screens (hdpi) and the other with smaller resolution for less density screens (mdpi or ldpi).
            Accessing images in layout xml file (for Ex main.xml):
<TextView ….. android:background=”@drawable/sample_image”/>
            Accessing from Java code :
button.setBackgroundResource(R.drawable.icon);
Working with color drawable resources
            We can define XML files that contain definitions for color drawable resources which are color rectangles that can be used as backgrounds.



            /res/values/myresources.xml
     <resources>
                         <drawable name="red_box">#ff0000</drawable>
                        <drawable name="blue_box">#0000ff</drawable>
                        <drawable name="green_box">#00ff00</drawable>
            </resources>
            Java Code to Access :
     TextView txt=(TextView)findViewById(R.id.txt);
            txt.setBackgroundResource(R.drawable.redBox);     (or)
            txt.setBackgroundResource(R.drawable.redBox);
Example on Color Resources :
Define an Android project, add a new Resource XML file in values folder, and modify the main.xml, run the project, observe the output.
/res/values/mycolor.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="red">#ff0000</color>
<color name="green">#00ff00</color>
<color name="blue">#0000ff</color>
</resources>
/res/layout/main.xml
<?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"
    android:id="@+id/background"
    >

<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Mallikarjun..Sathya "
    />
   
<!-- "white" defined in Android base set of colors -->
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:text="WHITE"
    android:textColor="@android:color/white"
    android:id="@+id/whitebutton"
 />
   
<!-- direct define textColor -->
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:text="RED"
    android:textColor="#ff0000"
    android:id="@+id/redbutton"
 />

<!-- "green" defined in mycolor.xml -->
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:text="GREEN"
    android:textColor="@color/green"
    android:id="@+id/greenbutton"
 />

<!-- "blue" defined in mycolor.xml -->
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content" 
    android:text="BLUE"
    android:textColor="@color/blue"
    android:id="@+id/bluebutton"
 />
</LinearLayout>


No comments:

Post a Comment

Ads Inside Post