您可以通过将资源ID作为方法参数在代码中使用的资源。例如,您可以设置一个ImageView的使用setImageResource()使用RES /绘制/ myimage.png资源:
ImageView imageView = (ImageView) findViewById(R.id.myimageview);
imageView.setImageResource(R.drawable.myimage);
您还可以使用资源的方法,你可以用getResources得到的一个实例检索各资源()。
// Load a background for the current screen from a drawable resource注意:你不应该通过修改R.java文件手工它是由AAPT工具生成当你的项目编译。任何更改都将覆盖下一次编译。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 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 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);
<Button android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="@string/submit" />句法
<?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 version="1.0" encoding="utf-8"?> <bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/other_drawable" />这听起来多余的,但使用替代资源时是非常有用的。了解更多关于创建别名资源。
<EditText id="text" android:layout_width="fill_parent" android:layout_height="wrap_content" android:textColor="?android:textColorSecondary" android:text="@string/hello_world" />
setListAdapter
(newArrayAdapter
<String>(this, android.R.layout.simple_list_item_1, myarray));