jubincn

导航

Android 4学习(4):概述 - Using Resources

参考:《Professional Android 4 Application Development


Andorid中的资源包括用户自定义资源和系统自带资源,这两种资源既可以在代码中使用,也可以在资源的定义中进行引用。

在代码中使用资源

Android在编译之后会自动生成一个静态类:R。R中包含对应资源类型的静态子类,如R.string, R.drawable。资源则用静态子类的字段表示,字段的名称正是资源的id,例如:R.string.app_name, R.drawable.icon。示例代码:

// Inflate a layout resource.
setContentView(R.layout.main);
// Display a transient dialog box that displays the error message string resource.
Toast.makeText(this, R.string.app_error, Toast.LENGTH_LONG).show();

Resource类提供了获取各种类型资源的getter方法,例如:

Resources myResources = getResources();
CharSequence styledText = myResources.getText(R.string.stop_message);
Drawable icon = myResources.getDrawable(R.drawable.app_icon);
int opaqueBlue = myResources.getColor(R.color.opaque_blue);
float borderWidth = myResources.getDimension(R.dimen.standard_border);
Animation tranOut;
tranOut = AnimationUtils.loadAnimation(this, R.anim.spin_shrink_fade);
ObjectAnimator animator = (ObjectAnimator)AnimatorInflater.loadAnimator(this, R.anim.my_animator);
String[] stringArray;
stringArray = myResources.getStringArray(R.array.string_array);
int[] intArray = myResources.getIntArray(R.array.integer_array);

在资源内部引用其他资源

使用@可以在资源定义文件内部引用其他资源,其格式如下:

attribute="@[packagename:]resourcetype/resourceidentifier"

示例代码:

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout

xmlns:android="http://schemas.android.com/apk/res/android"

android:orientation="vertical"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:padding="@dimen/standard_border">

<EditText

android:id="@+id/myEditText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="@string/stop_message"

android:textColor="@color/opaque_blue"

/>

</LinearLayout>

使用系统资源

Android系统自带了很多资源,我们可以在程序中使用系统的R静态类来获取和使用这些资源。无论在代码中还是在资源内部引用使用,系统资源和用户资源的方式都是一致的,只是引用的R类不同,资源的命名空间不同而已。下面是示例代码:

CharSequence httpError = getString(android.R.string.httpErrorBadUrl);

<EditText

android:id="@+id/myEditText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="@android:string/httpErrorBadUrl"

android:textColor="@android:color/darker_gray"

/>

引用当前主题的资源

Android允许程序

获取当前主题的资源,如颜色等信息,从而使程序员可以方便地提供更为一致的界面,增强用户体验。使用?android:可以获取当前主题下的资源,例如:

<EditText

android:id="@+id/myEditText"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="@android:string/httpErrorBadUrl"

android:textColor="?android:textColor"

/>


posted on 2013-10-10 22:23  jubincn  阅读(274)  评论(0编辑  收藏  举报