阅读(1054) (0)

Android 图片资源

2017-01-09 14:51:05 更新

Android生成放置在/res/drawable子目录中的图像文件的资源ID。

支持的图像类型包括.gif,.jpg和.png。此目录中的每个图像文件都从其基本文件名生成唯一的ID。

如果图像文件名为 sample_image.jpg ,那么生成的资源ID是 R.drawable.sample_image

对于具有相同基本文件名的两个文件名,将出现错误。将忽略 /res/drawable 下的子目录。

例子

以下代码显示如何在XML布局定义中使用图像资源。

<Button
      android:id="@+id/button1"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:text="Dial"
      android:background="@drawable/sample_image"
/>

下面的代码显示了如何检索Java中的图像,并将其设置为类似于按钮的UI对象。

BitmapDrawable d = activity.getResources().getDrawable(R.drawable.sample_image);
button.setBackgroundDrawable(d);

//or you can set the background directly from the Resource Id
button.setBackgroundResource(R.drawable.sample_image);

Android还支持一种特殊类型的图像,称为可拉伸图像。