1、Android中的资源介绍
Android中的资源是指非代码部分,如图片、mp3、字符串、xml文件等。在一个Android工程中,res和assets这两个文件夹用来保护资源文件。
不同点:
- res中的资源可以通过R资源类访问,res中包含的子文件夹有:anim(xml动画)、drawable(图片)、layout(布局文件)、menu(菜单)、raw(二进制文件)、values(常量值)、xml(xml文件)
- assets中保存的一般是原始的文件,例如MP3
- 文件、Android程序不能通过R类直接访问,必须通过AssetManager类以二进制流的形式来读取
2、使用资源的两种方式
- 使用context的getResources()方法得到Resources对象
- 在其他资源中引用资源的一般格式
(① @[包名称:]资源类型/资源名称 ②R.资源类型.资源名称)
3、颜色资源的使用
颜色值的定义是通过RGB三原色来定义的,颜色资源xml文件的定义。
资源位置 | res/values/colors.xml |
---|---|
获得颜色方法 | Resources.getColor( ) |
引用资源格式 | java中:R.color.color_name |
xml中:@color/color_name |
<resources>
<color name="text_color">#ff0000</color>
<color name="bg_color">#00ff00</color>
</resources>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="test"
android:text="Button"
tools:layout_editor_absoluteX="158dp"
tools:layout_editor_absoluteY="270dp"
tools:ignore="MissingConstraints" />
public void test(View view){
int color= this.getResources().getColor(R.color.bg_color);
Toast.makeText(this, ""+color, Toast.LENGTH_SHORT).show();
this.getWindow().setBackgroundDrawableResource(R.color.bg_color);
}
点击按钮前:
点击按钮后:
4、字符串资源的使用
我们使用Context.getString()方法,通过传递资源ID参数来得到该字符串,也可以在其他资源文件中引用字符串资源,引用格式为“@string/字符串资源名称”。
5、尺寸资源的使用