android资源访问

       上一节描述了android中的资源类型以及资源的的匹配问题,这一节将为大家描述如何去访问在上一节提供的资源。

        一旦你为应用程序提供了各种资源,那么你就可以使用该资源的ID值引用该资源,而所有资源的id都定义在R这个类中,R类有android编译工具自动产生不需要人工干预。所有在res目录下的资源文件都能够在R中找到ID。

        资源ID的组成部分:

  • the resource Type(资源类型):如drawable、string、layout、etc。
  • the resource Name(资源名称):文件名(去除后缀),android:name的值。

资源使用的两种方式:

  •  编码方式:
使用在R类中的整型值:R.string.hello
  • 在xml文件中
使用特殊的xml语法应用R类中的资源ID:@string/hello

编码使用介绍:

编码使用资源的引用规则:
[<package_name>.]R.<resource_type>.<resource_name>
    android.R.color.black
    R.color.black

将资源ID当做参数传递个方法
    ImageView imageView =(ImageView) findViewById(R.id.myimageview);
    imageView.setImageResource(R.drawable.myimage);
通过Resouce类查询资源
    getResources().getColor(R.color.black)
some case:
// 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 screensetContentView(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使用介绍

xml中使用规则:
@[<package_name>:]<resource_type>/<resource_name>
<Button
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/submit"/>
some case:
<?xml version="1.0" encoding="utf-8"?><resources>
   <colorname="opaque_red">#f00</color>
   <stringname="hello">Hello!</string></resources>

<?xml version="1.0" encoding="utf-8"?><EditTextxmlns: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"?><EditTextxmlns: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"/>

 样式的引用:

使用规则:
?[<package_name>:][<resource_type>/]<resource_name>
<EditTextid="text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:textColor="?android:textColorSecondary"
    android:text="@string/hello_world"/>

猜你喜欢

转载自xxmy.iteye.com/blog/1976946
今日推荐