在代码中使用资源,只是要知道所有资源ID 和你的被编译的资源是什么类型。
下面是一个引用资源的语法:R.resource_type.resource_name
或者android.R.resource_type.resource_name
其中resource_type 是R 的子类,保存资源的一个特定类型。resource_name 时在XML 文件定义的资源的name 属性,或者有其他文件类型为资源定义的文件名(不包含扩展名)。
每一种资源类型都会根据其类型加为一个特定的R 子类;要了解R 的哪一个子类是关于你的资源类型的,请参考资源参考(resource reference)文档。
被你的应用程序编译的资源可以不加包名引用(就像R.resource_type.resource_name 这样简单)。
Android 包含了很多标准资源,如屏幕样式和按钮背景。
要在代码中引用这些资源,你必须使用android 进行限定,如android.R.drawable.button_background
。
这里有一些在代码中使用已编译资源的正确和错误用法的例子。// Load a background for the current screen from a drawable
resource.
this.getWindow().setBackgroundDrawableResource(R.drawable.my_ba
ckground_image);
// WRONG Sending a string resource reference into a
// method that expects a string.
this.getWindow().setTitle(R.string.main_title);
// RIGHT Need to get the title from the Resources wrapper.
this.getWindow().setTitle(Resources.getText(R.string.main_title)
);
// Load a custom layout for the current screen.
setContentView(R.layout.main_screen);
// Set a slide in animation for a ViewFlipper object.
mFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
R.anim.hyperspace_in));
// Set the text on a TextView object.
TextView msgTextView = (TextView)findViewByID(R.id.msg);
msgTextView.setText(R.string.hello_message);