Wednesday, 30 January 2013

Android Development Tutorial (Based on Android 4.1) class-6

Using Resources


1. Reference to resources in code


The Resources class allows to access individual resources. An instance of Resources can get access via the getResources() method of the Context class.

The Resources class is also used by other Android classes, for example the following code shows how to create a Bitmap file from a reference ID.

code1

2. Reference to resources in XML files


In your XML files, for example your layout files, you can refer to other resources via the @ sign.

For example, if you want to refer to a color which is defined in a XML resource, you can refer to it via @color/your_id. Or if you defined a "hello" string in an XML resource, you could access it via @string/hello.

3. Activities and Layouts


The user interface for Activities is defined via layouts. The layout defines the included Views (widgets) and their properties.

A layout can be defined via Java code or via XML. In most cases the layout is defined as an XML file.

XML based layouts are defined via a resource file in the /res/layout folder. This file specifies the ViewGroups, Views, their relationship and their attributes for this specific layout.

If a View needs to be accessed via Java code, you have to give the View a unique ID via the android:id attribute. To assign a new ID to a View use @+id/yourvalue . The following shows an example in which a Button gets the button1 ID assigned.

code2

By conversion this will create and assign a new yourvalue ID to the corresponding View. In your Java code you can later access a View via the method findViewById(R.id.yourvalue).

Defining layouts via XML is usually the preferred way as this separates the programming logic from the layout definition. It also allows the definition of different layouts for different devices. You can also mix both approaches.

Related Topics : Android Development Tutorial (Based on Android 4.1) class-1

Android Development Tutorial (Based on Android 4.1) class-2


Android Development Tutorial (Based on Android 4.1) class-3


Android Development Tutorial (Based on Android 4.1) class-4


Android Development Tutorial (Based on Android 4.1) class-5

No comments:

Post a Comment