IMPORTANT: Per accedir als fitxer de subversion: http://acacha.org/svn (sense password). Poc a poc s'aniran migrant els enllaços. Encara però funciona el subversion de la farga però no se sap fins quan... (usuari: prova i la paraula de pas 123456)

Android App Resources

Una bona aplicació Android és més que només codi. Els recursos d'una aplicació Android (Android App Resources) són els fitxers addicionals que representen el contingut estàtic que el codi utilitzar (bitmaps, definicions de layouts, strings de la interfície, etc.)

Seguint els típics i aconsellables paradigmes de disseny, és altament recomanable externalitzar els recursos com les imatges o els textos del codi font.

Això té múltiples avantatges, per exemple:

  • Suportar diferents configuracions. Per exemple, diferents idiomes o mides de pantalla.
  • Tot això sense haver de fer modificacions del codi per tal d'adaptar l'aplicació a nous possibles dispositius o configuracions fet molt important per que contínuament surten nous dispositius amb noves característiques.

Podem trabar 2 tipus de recursos:

  • Recursos per defecte (default resources): Són els recursos que s'utilitzaran per defecte independentment de la configuració del dispositiu o quan no s'especifiquen recursos alternatius per a la configuració actual.
  • Recursos alternatius (Alternative resources): són els que es disseyen per a una configuració específica. Per especificar que un conjunt de recursos són per a una configuració especifica, s'afegeix un sufix al nom de la carptea on estan els recursos. Aquest sufix es coneix com a configuration qualifier.
Appresourcesfp1.png
Appresourcesfp2.png

Creem la taula de les carpetes (segons el tipus de recurs) que us podeu trobar a dins de la carpeta res.

Directori Tipus de Resource
animator/ Fitxers XML que defineixen propietats de lees animacions
anim/ fitxers XML que defineixen tween animations
color/ XML files that define a state list of colors. See Color State List Resource
drawable/ Bitmap files (.png, .9.png, .jpg, .gif) or XML files that are compiled into the following drawable resource subtypes:

- Bitmap files - Nine-Patches (re-sizable bitmaps) - State lists - Shapes - Animation drawables - Other drawables - Drawable Resources

layout/ Fitxers XML que defineixen layouts de la interfície gràfica. Vegeu Layout Resources.
menu/ Fitxers XML que defineixen menús d'aplicaciones, com els menús Options Menu, Context Menu, o Sub Menu. Vegeu Menu Resource.
raw/ Aquest és un directori tipus calix de sastre, que permet guardar qualsevol tipus de recurs en cru (raw). Es poden obrir aquests recursos amb com a InputStream, utilitzant Resources.openRawResource() i passant com a paràmetre el resource ID, que és R.raw.filename
values/ Conté fitxers XML que contenen valors simples, com strings, enters o colors. A diferencia de les altres carpetes on cada fitxers descriu un recurs, aquí s'utilitza un sol fitxers per a tots els recursos del mateix tipus. Es poden posar els noms que es vulguin però es recomana:

- arrays.xml: per definir vectors de recursos (aka typed arrays). - colors.xml: per valors de colors - dimens.xml: pre valors de dimensions - strings.xml: per a valors de text. - styles.xml: per a definir Android styles. Vegeu String Resources, Style Resource, i altres Resource Types.

xml/ Permet guardar fixers XML de qualsevol tipus. En temps d'execución aquests fitxers estan disponibles amb Resources.getXML(). Serveix per exemple per guardar fitxers de configuració XML
Link Tots els Resources aquí


Configuration Qualifier Values Description
MCC and MNC Examples:mcc310
mcc310-mnc004
mcc208-mnc00

etc.

The mobile country code (MCC), optionally followed by mobile network code (MNC)

from the SIM card in the device. For example, mcc310 is U.S. on any carrier, mcc310-mnc004 is U.S. on Verizon, and mcc208-mnc00 is France on

Orange.

If the device uses a radio connection (GSM phone), the MCC and MNC values come from the SIM card.

You can also use the MCC alone (for example, to include country-specific legal

resources in your application). If you need to specify based on the language only, then use the language and region qualifier instead (discussed next). If you decide to use the MCC and

MNC qualifier, you should do so with care and test that it works as expected.

Also see the configuration fields <a href="/reference/android/content/res/Configuration.html#mcc">mcc</a>, and <a href="/reference/android/content/res/Configuration.html#mnc">mnc</a>, which indicate the current mobile country code and mobile network code, respectively.

Language and region Examples:
en
fr
en-rUS
fr-rFR
fr-rCA

etc.

The language is defined by a two-letter <a

href="http://www.loc.gov/standards/iso639-2/php/code_list.php">ISO 639-1</a> language code, optionally followed by a two letter <a href="http://www.iso.org/iso/en/prods-services/iso3166ma/02iso-3166-code-lists/list-en1.html">ISO 3166-1-alpha-2</a> region code (preceded by lowercase "r").

The codes are not case-sensitive; the r prefix is used to distinguish the region portion.

You cannot specify a region alone.

This can change during the life

of your application if the user changes his or her language in the system settings. See <a href="runtime-changes.html">Handling Runtime Changes</a> for information about

how this can affect your application during runtime.

See <a href="localization.html">Localization</a> for a complete guide to localizing your application for other languages.

Also see the <a href="/reference/android/content/res/Configuration.html#locale">locale</a> configuration field, which indicates the current locale.

smallestWidth sw<N>dp

Examples:
sw320dp
sw600dp
sw720dp
etc.

The fundamental size of a screen, as indicated by the shortest dimension of the available

screen area. Specifically, the device's smallestWidth is the shortest of the screen's available height and width (you may also think of it as the "smallest possible width" for the screen). You can use this qualifier to ensure that, regardless of the screen's current orientation, your

application's has at least <N> dps of width available for it UI.

For example, if your layout requires that its smallest dimension of screen area be at

least 600 dp at all times, then you can use this qualifer to create the layout resources, res/layout-sw600dp/. The system will use these resources only when the smallest dimension of available screen is at least 600dp, regardless of whether the 600dp side is the user-perceived height or width. The smallestWidth is a fixed screen size characteristic of the device; the

device's smallestWidth does not change when the screen's orientation changes.

The smallestWidth of a device takes into account screen decorations and system UI. For

example, if the device has some persistent UI elements on the screen that account for space along the axis of the smallestWidth, the system declares the smallestWidth to be smaller than the actual screen size, because those are screen pixels not available for your UI. Thus, the value you use should be the actual smallest dimension required by your layout (usually, this value is the

"smallest width" that your layout supports, regardless of the screen's current orientation).

Some values you might use here for common screen sizes:

  • 320, for devices with screen configurations such as:
    • 240x320 ldpi (QVGA handset)
    • 320x480 mdpi (handset)
    • 480x800 hdpi (high density handset)
  • 480, for screens such as 480x800 mdpi (tablet/handset).
  • 600, for screens such as 600x1024 mdpi (7" tablet).
  • 720, for screens such as 720x1280 mdpi (10" tablet).

When your application provides multiple resource directories with different values for

the smallestWidth qualifier, the system uses the one closest to (without exceeding) the

device's smallestWidth.

Added in API level 13.

Also see the <a

href="/guide/topics/manifest/supports-screens-element.html#requiresSmallest">android:requiresSmallestWidthDp</a> attribute, which declares the minimum smallestWidth with which your application is compatible, and the <a href="/reference/android/content/res/Configuration.html#smallestScreenWidthDp">smallestScreenWidthDp</a> configuration field, which holds the

device's smallestWidth value.

For more information about designing for different screens and using this

qualifier, see the <a href="/guide/practices/screens_support.html">Supporting

Multiple Screens</a> developer guide.

Available width w<N>dp

Examples:
w720dp
w1024dp
etc.

Specifies a minimum available screen width, in dp units at which the resource

should be used—defined by the <N> value. This configuration value will change when the orientation

changes between landscape and portrait to match the current actual width.

When your application provides multiple resource directories with different values

for this configuration, the system uses the one closest to (without exceeding) the device's current screen width. The value here takes into account screen decorations, so if the device has some persistent UI elements on the left or right edge of the display, it uses a value for the width that is smaller than the real screen size, accounting

for these UI elements and reducing the application's available space.

Added in API level 13.

Also see the <a href="/reference/android/content/res/Configuration.html#screenWidthDp">screenWidthDp</a> configuration field, which holds the current screen width.

For more information about designing for different screens and using this

qualifier, see the <a href="/guide/practices/screens_support.html">Supporting

Multiple Screens</a> developer guide.

Available height h<N>dp

Examples:
h720dp
h1024dp
etc.

Specifies a minimum available screen height, in "dp" units at which the resource

should be used—defined by the <N> value. This configuration value will change when the orientation

changes between landscape and portrait to match the current actual height.

When your application provides multiple resource directories with different values

for this configuration, the system uses the one closest to (without exceeding) the device's current screen height. The value here takes into account screen decorations, so if the device has some persistent UI elements on the top or bottom edge of the display, it uses a value for the height that is smaller than the real screen size, accounting for these UI elements and reducing the application's available space. Screen decorations that are not fixed (such as a phone status bar that can be hidden when full screen) are not accounted for here, nor are window decorations like the title bar or action bar, so applications must be prepared to deal with a somewhat smaller space than they specify.

<p>Added in API level 13.

Also see the <a href="/reference/android/content/res/Configuration.html#screenHeightDp">screenHeightDp</a> configuration field, which holds the current screen width.

For more information about designing for different screens and using this

qualifier, see the <a href="/guide/practices/screens_support.html">Supporting

Multiple Screens</a> developer guide.

Screen size small
normal
large
xlarge
  • small: Screens that are of similar size to a

    low-density QVGA screen. The minimum layout size for a small screen is approximately 320x426 dp units. Examples are QVGA low density and VGA high

    density.
  • normal: Screens that are of similar size to a

    medium-density HVGA screen. The minimum layout size for a normal screen is approximately 320x470 dp units. Examples of such screens a WQVGA low density, HVGA medium density, WVGA

    high density.
  • large: Screens that are of similar size to a

    medium-density VGA screen. The minimum layout size for a large screen is approximately 480x640 dp units.

    Examples are VGA and WVGA medium density screens.
  • xlarge: Screens that are considerably larger than the traditional

    medium-density HVGA screen. The minimum layout size for an xlarge screen is approximately 720x960 dp units. In most cases, devices with extra large screens would be too large to carry in a pocket and would most likely

    be tablet-style devices. Added in API level 9.

Note: Using a size qualifier does not imply that the

resources are only for screens of that size. If you do not provide alternative resources with qualifiers that better match the current device configuration, the system may use

whichever resources are the <a href="#BestMatch">best match</a>.

Caution: If all your resources use a size qualifier that

is larger than the current screen, the system will not use them and your

application will crash at runtime (for example, if all layout resources are tagged with the xlarge qualifier, but the device is a normal-size screen).

Added in API level 4.

See <a href="/guide/practices/screens_support.html">Supporting Multiple Screens</a> for more information.

Also see the <a href="/reference/android/content/res/Configuration.html#screenLayout">screenLayout</a> configuration field,

which indicates whether the screen is small, normal,

or large.

Screen aspect long
notlong
  • long: Long screens, such as WQVGA, WVGA, FWVGA
  • notlong: Not long screens, such as QVGA, HVGA, and VGA

Added in API level 4.

This is based purely on the aspect ratio of the screen (a "long" screen is wider). This is not related to the screen orientation.

Also see the <a href="/reference/android/content/res/Configuration.html#screenLayout">screenLayout</a> configuration field, which indicates whether the screen is long.

Screen orientation port
land<!--
square -->
  • port: Device is in portrait orientation (vertical)
  • land: Device is in landscape orientation (horizontal)
  • <!-- Square mode is currently not used. -->

This can change during the life of your application if the user rotates the

screen. See <a href="runtime-changes.html">Handling Runtime Changes</a> for information about

how this affects your application during runtime.

Also see the <a href="/reference/android/content/res/Configuration.html#orientation">orientation</a> configuration field, which indicates the current device orientation.

UI mode car
desk
television
<code>appliance
  • car: Device is displaying in a car dock
  • desk: Device is displaying in a desk dock
  • television: Device is displaying on a television, providing

    a "ten foot" experience where its UI is on a large screen that the user is far away from, primarily oriented around DPAD or other

    non-pointer interaction
  • appliance: Device is serving as an appliance, with no display

Added in API level 8, television added in API 13.

For information about how your app can respond when the device is inserted into or

removed from a dock, read <a href="/training/monitoring-device-state/docking-monitoring.html">Determining

and Monitoring the Docking State and Type</a>.

This can change during the life of your application if the user places the device in a

dock. You can enable or disable some of these modes using <a href="/reference/android/app/UiModeManager.html">UiModeManager</a>. See <a href="runtime-changes.html">Handling Runtime Changes</a> for

information about how this affects your application during runtime.

Night mode night
notnight
  • night: Night time
  • notnight: Day time

Added in API level 8.

This can change during the life of your application if night mode is left in

auto mode (default), in which case the mode changes based on the time of day. You can enable or disable this mode using <a href="/reference/android/app/UiModeManager.html">UiModeManager</a>. See <a href="runtime-changes.html">Handling Runtime Changes</a> for information about how this affects your

application during runtime.

Screen pixel density (dpi) ldpi
mdpi
hdpi
xhdpi
nodpi
tvdpi
  • ldpi: Low-density screens; approximately 120dpi.
  • mdpi: Medium-density (on traditional HVGA) screens; approximately 160dpi.
  • hdpi: High-density screens; approximately 240dpi.
  • xhdpi: Extra high-density screens; approximately 320dpi. Added in API Level 8
  • nodpi: This can be used for bitmap resources that you do not want to be scaled to match the device density.
  • tvdpi: Screens somewhere between mdpi and hdpi; approximately 213dpi. This is

    not considered a "primary" density group. It is mostly intended for televisions and most apps shouldn't need it—providing mdpi and hdpi resources is sufficient for most apps and

    the system will scale them as appropriate. This qualifier was introduced with API level 13.

There is a 3:4:6:8 scaling ratio between the four primary densities (ignoring the tvdpi density). So, a 9x9 bitmap in ldpi is 12x12 in mdpi, 18x18 in hdpi and 24x24 in xhdpi.

If you decide that your image resources don't look good enough on a television or

other certain devices and want to try tvdpi resources, the scaling factor is 1.33*mdpi. For

example, a 100px x 100px image for mdpi screens should be 133px x 133px for tvdpi.

Note: Using a density qualifier does not imply that the

resources are only for screens of that density. If you do not provide alternative resources with qualifiers that better match the current device configuration, the system may use

whichever resources are the <a href="#BestMatch">best match</a>.

See <a href="/guide/practices/screens_support.html">Supporting Multiple

Screens</a> for more information about how to handle different screen densities and how Android

might scale your bitmaps to fit the current density.

Touchscreen type notouch
finger
  • notouch: Device does not have a touchscreen.
  • finger: Device has a touchscreen that is intended to be used through direction interaction of the user's finger.

Also see the <a href="/reference/android/content/res/Configuration.html#touchscreen">touchscreen</a> configuration field, which indicates the type of touchscreen on the device.

Keyboard availability keysexposed
keyshidden
keyssoft
  • keysexposed: Device has a keyboard available. If the device has a

    software keyboard enabled (which is likely), this may be used even when the hardware keyboard is not exposed to the user, even if the device has no hardware keyboard. If no software keyboard is provided or it's disabled, then this is only used when a hardware keyboard is

    exposed.
  • keyshidden: Device has a hardware keyboard available but it is hidden and the device does not have a software keyboard enabled.
  • keyssoft: Device has a software keyboard enabled, whether it's visible or not.

If you provide keysexposed resources, but not keyssoft

resources, the system uses the keysexposed resources regardless of whether a

keyboard is visible, as long as the system has a software keyboard enabled.

This can change during the life of your application if the user opens a hardware

keyboard. See <a href="runtime-changes.html">Handling Runtime Changes</a> for information about how

this affects your application during runtime.

Also see the configuration fields <a href="/reference/android/content/res/Configuration.html#hardKeyboardHidden">hardKeyboardHidden</a> and <a href="/reference/android/content/res/Configuration.html#keyboardHidden">keyboardHidden</a>, which indicate the visibility of a hardware keyboard and and the visibility of any kind of keyboard (including software), respectively.

Primary text input method nokeys
qwerty
12key
  • nokeys: Device has no hardware keys for text input.
  • qwerty: Device has a hardware qwerty keyboard, whether it's visible to the

    user

    or not.
  • 12key: Device has a hardware 12-key keyboard, whether it's visible to the user or not.

Also see the <a href="/reference/android/content/res/Configuration.html#keyboard">keyboard</a> configuration field, which indicates the primary text input method available.

Screen dimensions Examples:
320x240
640x480

etc.

The larger dimension must be specified first. This configuration is deprecated

and should not be used. Instead use "screen size," "wider/taller screens," and "screen

orientation" described above.

-->

Platform Version (API level) Examples:
v3
v4
v7

etc.

The API level supported by the device. For example, v1 for API level

1 (devices with Android 1.0 or higher) and v4 for API level 4 (devices with Android 1.6 or higher). See the <a href="/guide/topics/manifest/uses-sdk-element.html#ApiLevels">Android API levels</a> document for more information

about these values.

Caution: Android 1.5 and 1.6 only match resources

with this qualifier when it exactly matches the platform version. See the section below about <a

href="#KnownIssues">Known Issues</a> for more information.


Build & Running

Br1ferranpallares.png

Imatge 1

En la imatge 1 podem veure el procediment resumit de construcció i execució de les aplicacions Android i els components que intervenen.


Br2ferranpallares.png

Imatge 2

En la imatge 2 veiem tot el proces amb mes detall.


Apkferranpallares.png Imatge 3 Apk1ferranpallares.png Imatge 4


En la imatge 3 veiem els documents que estan a l'interior d'una .apk d'una aplicacio personal.

Com podem veure, si comparem la imatge 1 i la 3, veiem que hi ha el classes.dex classes, binari, resources.arsc recursos compilats, binari, l' AndroidManifest.xml aquets fitxer indica les metadades de l'aplicacio, es autonom i es el fitxer minim que ha de contenir tota aplicació minima, i les diferents carpetes.

En la imatge 4 veiem tot els que esta a l'interior de la carpeta res dintre del apk.

Dins d'un paquet Android cal trobar:

  • Fitxers compilats .dex (són com els fitxers .class de Java però adaptats a la màquina virtual Dalvik ( byte code))
  • Una versió binaria del fitxers AndroidManifest.xml
  • Recursos compilats (resources.arsc) i recursos no compilats

Si s'utilitza Eclipse, el Plugin ADT construeix l'aplicació de forma incremental a mesura que es fan canvis al codi font. Eclipse crea automàticament un fitxer apk i el guarda a la carpeta bin del projecte.

Si no s'utilitza Eclipse, es pot construir el projecte amb Ant i un fitxer build.xml.

Al crear un apk s'ha de marcar com debug mode o release mode. El debug mode és el més utilitzat quan es desenvolupa però al publicar l'aplicació (per exemple Google Play) s'han de signar utilitzant una clau privada.

El procés general és:

  • L'eina Android Asset Packaging Tool (aapt) agafa els App Android Resources com per exemple el fitxer AndroidManifest.xml i la resta de fitxers XML de les activitats i les compila. També es crear la clase R.java per tal de que es pugui utilitzar al codi Java.
  • L'eina aidl converteix qualsevol interfície .aidl en interfície Java
  • Tot el codi, incloent el propi, la classe R.java i els fitxers aidl són compilats pel compilador Java.
  • L'eina dex converteix els fitxers .class a fitxers .hex (Dalvik byte code). Totes les llibreries de tercers i fitxers .class inclosos també són convertits a .hex i empaquetats al fitxer final apk.
  • Tots els recursos no compilats (p.ex. les imatges), i també els fitxers .dex són enviats a l'eina apkbuilder per tal que crei el apk.
  • Un cop el apk s'ha creat es signa
  • Si l'aplicació es signa en release mode, aleshores s'utilitza l'eina zipalign. Això permet disminuir el ús de memòria quan l'aplicació spexecuta a un dispositiu real.


Accedint al recurs des del codi

Que és de la clase Context, de la que són pare totes les activitats.

El paràmetre més important d'un recurs és el seu Resource ID (identificador del recurs). L'aplicació:

aapt

és l'eina encarregada de crear la classe R. Quan l'aplicació es construida per Eclipse, aapt genera la clase R que conté els identificadors de recursos de tots els recursos de la carpeta res. Per cada recurs hi ha una subclase R (per exemple R.drawable és una subclase amb tots els recursos de tipus R). Per a cada recurs hi ha un static integer que l'identifica, per exemple:

R.drawable.icon

Un altre exemple molt comú és el següent codi:

@Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
  }


Aquest integer (icon al exemple 1) és el resource ID.

Tot i que la classe R és on estan tots els IDs especificats, no cal mirar al seu interior per conèixer els IDs, ja que sempre es composen de la següent forma:

  • El tipus de recurs: tots els recursos estan dins d'un tipus com string, drawable o layout. Vegeu Resource Types
  • El nom de recurs: sempre coincideix amb el nom del fitxer sense tenir en compte la extensión o en el cas dels values el atribut XML android:name si el recurs és un valor simple.

Hi ha dos formes d'accedir als recursos:

  • Accedir des del codi font: S'utilitza l'especificat anteriorment. Els detalls els trobeu en aquest mateix apartat. Per exemple: R.string.hello és un exemple clar de com obtenir el Resource ID d'un recurs.
  • Accedir des de fitxers XML: s'utilitza una sintaxi especial que s'explica al següent apartat.

Un exemple de com obtenir una recurs de tipus imatge:

ImageView imageView = (ImageView) findViewById(R.id.myimageview);
imageView.setImageResource(R.drawable.myimage);


Accedint als recursos des de fitxers XML

Dins d'un fitxer XML es poden definir valors XML a els atributs i elements XML fent referencia a recursos Android existents. Per exemple als fitxers de layout XML (que per ells mateixos són també un recurs Android) es típic fer referencia a recursos Android de tipus valor de text (Strings). Un exemple:

<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/submit" />
aquest extracte d'un fitxer XMl de Layout representa un Botó el text del qual pren el valor del recurs de text @string/submit.

La sintaxi és la següent:

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

On:

  • <package_name>: és un valor opcional que indica el nom del paquet a on es troba el recurs. No cal posar-ho quan s'utilitzant recursos del mateix paquet.
  • <resource_type>: és la subclase de la classe R, o el que coneixem com a tipus de recurs.
  • <resource_name>: és o el nom del fitxer sense la extensió del fitxer que conté el recurs, o en le cas de recursos del tipus valor simple el valor de l'atribut android:name.


Vegueu també

Web Oficial App Resources