Once you provide a resource in your application (discussed inProviding Resources), you can apply it by referencing its resource ID. All resource IDs are defined in your project'sRclass, which theaapttool automatically generates.

When your application is compiled,aaptgenerates theRclass, which contains resource IDs for all the resources in yourres/directory. For each type of resource, there is anRsubclass (for example,R.drawablefor all drawable resources), and for each resource of that type, there is a static integer (for example,R.drawable.icon). This integer is the resource ID that you can use to retrieve your resource.

Although theRclass is where resource IDs are specified, you should never need to look there to discover a resource ID. A resource ID is always composed of:

  • Theresource type: Each resource is grouped into a "type," such asstring,drawable, andlayout. For more about the different types, seeResource Types.
  • Theresource name, which is either: the filename, excluding the extension; or the value in the XMLandroid:nameattribute, if the resource is a simple value (such as a string).

There are two ways you can access a resource:

  • In code:Using a static integer from a sub-class of yourRclass, such as:
    R.string.hello

    stringis the resource type andhellois the resource name. There are many Android APIs that can access your resources when you provide a resource ID in this format. SeeAccessing Resources in Code.

  • In XML:Using a special XML syntax that also corresponds to the resource ID defined in yourRclass, such as:
    @string/hello

    stringis the resource type andhellois the resource name. You can use this syntax in an XML resource any place where a value is expected that you provide in a resource. SeeAccessing Resources from XML.

Accessing Resources in Code

You can use a resource in code by passing the resource ID as a method parameter. For example, you can set anImageViewto use theres/drawable/myimage.pngresource usingsetImageResource():

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

You can also retrieve individual resources using methods inResources, which you can get an instance of withgetResources().

Access to Original Files

While uncommon, you might need access your original files and directories. If you do, then saving your files inres/won't work for you, because the only way to read a resource fromres/is with the resource ID. Instead, you can save your resources in theassets/directory.

Files saved in theassets/directory arenotgiven a resource ID, so you can't reference them through theRclass or from XML resources. Instead, you can query files in theassets/directory like a normal file system and read raw data usingAssetManager.

However, if all you require is the ability to read raw data (such as a video or audio file), then save the file in theres/raw/directory and read a stream of bytes usingopenRawResource().

Syntax

Here's the syntax to reference a resource in code:

[<package_name>.]R.<resource_type>.<resource_name>
  • <package_name>is the name of the package in which the resource is located (not required when referencing resources from your own package).
  • <resource_type>is theRsubclass for the resource type.
  • <resource_name>is either the resource filename without the extension or theandroid:nameattribute value in the XML element (for simple values).

SeeResource Typesfor more information about each resource type and how to reference them.

Use cases

There are many methods that accept a resource ID parameter and you can retrieve resources using methods inResources. You can get an instance ofResourceswithContext.getResources().

Here are some examples of accessing resources in code:

// Load a background for the current screen from a drawable resourcegetWindow().setBackgroundDrawableResource(R.drawable.my_background_image) ;// Set the Activity title by getting a string from the Resources object, because// this method requires a CharSequence rather than a resource IDgetWindow().setTitle(getResources().getText(R.string.main_title));// Load a custom layout for the current screensetContentView(R.layout.main_screen);// Set a slide in animation by getting an Animation from the Resources objectmFlipper.setInAnimation(AnimationUtils.loadAnimation(this,    R.anim.hyperspace_in));// Set the text on a TextView object using a resource IDTextView msgTextView = (TextView) findViewById(R.id.msg);msgTextView.setText(R.string.hello_message);

Caution:You should never modify theR.javafile by hand—it is generated by theaapttool when your project is compiled. Any changes are overridden next time you compile.

Accessing Resources from XML

You can define values for some XML attributes and elements using a reference to an existing resource. You will often do this when creating layout files, to supply strings and images for your widgets.

For example, if you add aButtonto your layout, you should use astring resourcefor the button text:

<Button  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:text="@string/submit" />

Syntax

Here is the syntax to reference a resource in an XML resource:

@[<package_name>:]<resource_type>/<resource_name>
  • <package_name>is the name of the package in which the resource is located (not required when referencing resources from the same package)
  • <resource_type>is theRsubclass for the resource type
  • <resource_name>is either the resource filename without the extension or theandroid:nameattribute value in the XML element (for simple values).

SeeResource Typesfor more information about each resource type and how to reference them.

Use cases

In some cases you must use a resource for a value in XML (for example, to apply a drawable image to a widget), but you can also use a resource in XML any place that accepts a simple value. For example, if you have the following resource file that includes acolor resourceand astring resource:

<?xml version="1.0" encoding="utf-8"?><resources> <color name="opaque_red">#f00</color> <string name="hello">Hello!</string></resources>

You can use these resources in the following layout file to set the text color and text string:

<?xml version="1.0" encoding="utf-8"?><EditText xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="fill_parent"  android:layout_height="fill_parent"  android:textColor="@color/opaque_red"  android:text="@string/hello" />

In this case you don't need to specify the package name in the resource reference because the resources are from your own package. To reference a system resource, you would need to include the package name. For example:

<?xml version="1.0" encoding="utf-8"?><EditText xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="fill_parent"  android:layout_height="fill_parent"  android:textColor="@android:color/secondary_text_dark"  android:text="@string/hello" />

Note:You should use string resources at all times, so that your application can be localized for other languages. For information about creating alternative resources (such as localized strings), seeProviding Alternative Resources. For a complete guide to localizing your application for other languages, seeLocalization.

You can even use resources in XML to create aliases. For example, you can create a drawable resource that is an alias for another drawable resource:

<?xml version="1.0" encoding="utf-8"?><bitmap xmlns:android="http://schemas.android.com/apk/res/android"  android:src="@drawable/other_drawable" />

This sounds redundant, but can be very useful when using alternative resource. Read more aboutCreating alias resources.

Referencing style attributes

A style attribute resource allows you to reference the value of an attribute in the currently-applied theme. Referencing a style attribute allows you to customize the look of UI elements by styling them to match standard variations supplied by the current theme, instead of supplying a hard-coded value. Referencing a style attribute essentially says, "use the style that is defined by this attribute, in the current theme."

To reference a style attribute, the name syntax is almost identical to the normal resource format, but instead of the at-symbol (@), use a question-mark (?), and the resource type portion is optional. For instance:

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

For example, here's how you can reference an attribute to set the text color to match the "primary" text color of the system theme:

<EditText id="text"  android:layout_width="fill_parent"  android:layout_height="wrap_content"  android:textColor="?android:textColorSecondary"  android:text="@string/hello_world" />

Here, theandroid:textColorattribute specifies the name of a style attribute in the current theme. Android now uses the value applied to theandroid:textColorSecondarystyle attribute as the value forandroid:textColorin this widget. Because the system resource tool knows that an attribute resource is expected in this context, you do not need to explicitly state the type (which would be?android:attr/textColorSecondary)—you can exclude theattrtype.

Accessing Platform Resources

Android contains a number of standard resources, such as styles, themes, and layouts. To access these resource, qualify your resource reference with theandroidpackage name. For example, Android provides a layout resource you can use for list items in aListAdapter:

setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myarray));

In this example,simple_list_item_1is a layout resource defined by the platform for items in aListView. You can use this instead of creating your own layout for list items. For more information, see theList Viewdeveloper guide.

一旦您提供您的应用程序(在讨论资源提供了参考资料),您可以通过引用其资源ID应用它。所有的资源ID在你的项目的定义- [R类,其中AAPT工具自动生成。

当你的应用程序编译,AAPT产生- [R类,其中包含资源ID为你的所有资源RES /目录下。对于每种类型的资源的,有一个ř子类(例如,R.drawable所有绘图资源),并且该类型的每一个资源,有一个静态的整数(例如,R.drawable.icon)。此整数,你可以用它来 ​​检索您的资源的资源ID。

虽然- [R类是在哪里被指定资源ID,你永远不应该需要看有没有发现一个资源ID。一个资源ID始终组成:

  • 资源类型:每个资源组合成一个“型,”比如可拉伸布局。欲了解更多有关不同类型,请参阅资源类型。
  • 资源名,它可以是:文件名 ​​,不包括扩展名;或XML值的android:名称属性,如果资源是一个简单的值(如字符串)。

有两种方式可以访问资源:

  • 在代码:从一个子类的的使用静态整数ř类,如:
    R.string.hello

    字符串是资源的类型和你好是资源名称。有很多时候,你提供这种格式的资源ID可以访问你的资源的Android的API。见在代码中访问资源。

  • 在XML中:使用也对应于在所定义的资源ID的特殊的XML语法ř类,如:
    @字符串/你好

    字符串是资源的类型和你好是资源名称。您可以在XML资源使用此语法,其中一个预期值,您在资源提供的任何地方。请参见从XML访问资源。

访问资源代码

您可以通过将资源ID作为方法参数在代码中使用的资源。例如,您可以设置一个ImageView的使用RES /绘制/ myimage.png使用资源setImageResource()

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

您也可以使用的方法获取各个 ​​资源的资源,你可以得到的一个实例getResources()

访问原始文件

虽然少见,你可能需要访问您的原始文件和目录。如果你这样做,然后保存在文件RES /不会为你工作,因为只有这样才能读取资源RES /与资源ID。相反,你可以在节约您的资源资产/目录下。

保存在文件中的资产/目录中没有给出一个资源ID,这样你就可以不通过引用它们- [R类或XML资源。相反,你可以查询文件的资产/像一个正常的文件系统目录和读取使用原始数据AssetManager

但是,如果要求所有的读取原始数据(如视频或音频文件)的能力,然后保存在文件RES /生/目录和读取的字节使用流openRawResource()

句法

下面是引用代码中的资源的语法:

[ <软件包> ] R上。<RESOURCE_TYPE> <RESOURCE_NAME>
  • <软件包>是在资源所在的包(从自己的包中引用资源时不要求)的名称。
  • <RESOURCE_TYPE>- [R为资源类型的子类。
  • <RESOURCE_NAME>要么是不带扩展名或资源文件名​​的android:名称在XML元素属性值(简单值)。

请参见资源类型有关每个资源类型,以及如何引用它们的更多信息。

用例

有许多接受一个资源ID参数的方法和您可以检索使用方法的资源资源。你可以得到的实例资源Context.getResources()

这里是在代码访问资源的一些例子:

//从绘制资源加载当前屏幕的背景getWindow () setBackgroundDrawableResourceř 绘制my_background_image ; 通过充分利用资源对象的字符串//设置活动标题,因为//此方法需要一个相当的CharSequence除资源ID getWindow () 的setTitlegetResources ()。gettext的ř 字符串main_title)); //将当前屏幕自定义布局的setContentViewř 布局main_screen); //设置动画的幻灯片从资源获得一个动画对象mFlipper setInAnimationAnimationUtils loadAnimation     ř 阿尼姆hyperspace_in)); //使用资源ID设置一个TextView对象上的文字TextView的msgTextView =  的TextView findViewById ř ID 味精); msgTextView 的setTextř 字符串的hello_message);

注意:你不应该修改R.java按文件手工它是由产生AAPT工具时,你的项目编译。任何更改都将覆盖下一次编译。

从XML访问资源

您可以使用到现有资源的引用一些XML元素和属性定义值。创建布局文件时,您会经常这样做,提供字符串和图像为您的小部件。

例如,如果你添加一个按钮到您的布局,你应该使用字符串资源的按钮上的文字:

<Button   android:layout_width = "fill_parent"   android:layout_height = "wrap_content"   android:text = " @string/submit "  />

句法

这里是在XML资源引用一个资源的语法:

@ [ <软件包>:] <RESOURCE_TYPE> / <RESOURCE_NAME>
  • <软件包>是在资源所在(来自同一个包引用资源时不需要)包的名称
  • <RESOURCE_TYPE>- [R为资源类型的子类
  • <RESOURCE_NAME>要么是不带扩展名或资源文件名​​的android:名称在XML元素属性值(简单值)。

请参见资源类型有关每个资源类型,以及如何引用它们的更多信息。

用例

在某些情况下,你必须在XML中使用资源的值(例如,在绘制的图像应用到小部件),但你也可以使用一个资源在XML中接受一个简单的值的任何地方。例如,如果您有包括以下资源文件颜色资源和字符串资源:

<?xml的version = "1.0" encoding = "utf-8" ?> <resources>  <color  name = "opaque_red" > #f00 </color>  <string  name = "hello" > Hello! </string> </resources>

您可以在下面的布局文件利用这些资源来设置文本的颜色和文本字符串:

<?xml的version = "1.0" encoding = "utf-8" ?> <EditText  xmlns:android = "http://schemas.android.com/apk/res/android"   android:layout_width = "fill_parent"   android:layout_height = "fill_parent"   android:textColor = " @color/opaque_red "   android:text = " @string/hello "  />

在这种情况下,你并不需要在资源引用指定包名,因为资源是从你自己的包。要引用一个系统资源,您将需要包括包名称。例如:

<?xml的version = "1.0" encoding = "utf-8" ?> <EditText  xmlns:android = "http://schemas.android.com/apk/res/android"   android:layout_width = "fill_parent"   android:layout_height = "fill_parent"   android:textColor = " @android:color/secondary_text_dark "   android:text = "@string/hello"  />

注意:你应该在任何时候使用字符串资源,让您的应用程序可以被本地化为其他语言。有关创建替代资源(如本地化的字符串)的信息,请参阅提供替代资源。对于一个完整的指南,您的本地化为其他语言的应用程序,请参见本地化。

你甚至可以使用的资源XML创建别名。例如,您可以创建一个可绘制资源是另一个绘制资源的别名:

<?xml的version = "1.0" encoding = "utf-8" ?> <bitmap  xmlns:android = "http://schemas.android.com/apk/res/android"   android:src = "@drawable/other_drawable"  />

这听起来多余的,但使用替代资源时是非常有用的。了解更多关于创建别名资源。

引用样式属性

style属性的资源可以让你引用了当前应用的主题属性的值。引用一个样式属性,您可以通过它们的造型来匹配当前主题提供的标准变化,而不是提供一个硬编码值以自定义UI元素的外观。引用样式属性本质上说,“使用由该属性定义的样式,在当前的主题。”

以引用的样式属性,名称语法几乎是相同的正常资源格式,但代替在符号(@),使用一个问号(),和资源类型部分是可选的。例如:

?[ < 软件包名称>:] [ < RESOURCE_TYPE > /] < RESOURCE_NAME >

例如,这里是你如何能参考设置文本颜色相匹配的系统主题的“主”文本颜色的属性:

<EditText  id = "text"   android:layout_width = "fill_parent"   android:layout_height = "wrap_content"   android:textColor = " ?android:textColorSecondary "   android:text = "@string/hello_world"  />

在这里,机器人:文字颜色属性指定当前主题样式属性的名称。Android现在使用适用于价值机器人:textColorSecondary样式属性作为值文字颜色:机器人在这个小部件。由于系统资源的工具知道一个属性资源在这样的背景下预期,你不需要明确说明类型(这将是机器人?ATTR / textColorSecondary) -您可以排除ATTR类型。

访问平台资源

机器人包含许多标准资源,如样式,主题,和布局。要访问这些资源,资格与你的资源引用的Android包名。例如,Android提供您可以使用列表中的项目布局资源ListAdapter

setListAdapter ArrayAdapter < 字符串>( 机器人ř 布局simple_list_item_1管理myarray中));

在这个例子中,simple_list_item_1管理是由平台用于在项定义的布局资源的ListView。您可以使用它代替列表项创建自己的布局。欲了解更多信息,请参阅列表视图开发指南


更多相关文章

  1. Android(安卓)java在窗口画图写字符串
  2. 在Activity中注册广播
  3. Android中十六进制颜色字符串转int的方法
  4. 内存优化二
  5. android 设置seekBar 和Progress背景色
  6. java.lang.RuntimeException: Unable to start activity Compone
  7. Http 以post方式获取数据
  8. VideoView
  9. android中用到的资源Color

随机推荐

  1. Android 软件开发之如何使用Eclipse Debu
  2. Android 视频 美颜SDK对比
  3. Android 动态解析网络布局
  4. Android Studio中新建assets文件的两种方
  5. Android OpenGL ES 基础:绘制三角形
  6. Android中高效的显示图片之二——在非UI
  7. 通过wifi连接android设备的方法
  8. 传记称乔布斯曾对Android强烈不满:拟要摧
  9. android 条码识别软件开发全解析:0
  10. Android UI设计常用尺寸及基本知识