Accessing Resources

阅读:http://developer.android.com/guide/topics/resources/accessing-resources.html

 

Although the R class 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:

  • The resource type: Each resource is grouped into a "type," such as string, drawable, and layout. For more about the different types, see Resource Types.
  • The resource name, which is either: the filename, excluding the extension; or the value in the XML android:name attribute, if the resource is a simple value (such as a string).

  R会为每一个res下的文件建立唯一的ID,ID的引用一般是 文件类型.文件名.文件扩展名。


 

 

有两个方法可以进行访问:1、代码中使用R.XXX.XXX进行访问;2、在布局文件使用类似@string/hello的方法进行访问;

 


 

 

You can use a resource in code by passing the resource ID as a method parameter. For example, you can set an ImageView to use the res/drawable/myimage.png resource using setImageResource():

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

You can also retrieve individual resources using methods in Resources, which you can get an instance of with getResources().

  语法:[<package_name>.]R.<resource_type>.<resource_name>


 

 

  资源使用举例:

  

// Load a background for the current screen from a drawable resource
getWindow().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 ID
getWindow().setTitle(getResources().getText(R.string.main_title));

// Load a custom layout for the current screen
setContentView(R.layout.main_screen);

// Set a slide in animation by getting an Animation from the Resources object
mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
        R.anim.hyperspace_in));

// Set the text on a TextView object using a resource ID
TextView msgTextView = (TextView) findViewById(R.id.msg);
msgTextView.setText(R.string.hello_message);

 

XML使用方法:

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

<?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" />

如果用自己包的文件就不用加包名了,但是如果使用系统的VALUES,则需要加上包名。

 

 

 

posted @ 2013-10-24 22:14  yutoulck  阅读(151)  评论(0编辑  收藏  举报