android中的R类
时间: 2024-05-14 17:20:03 浏览: 13
在 Android 中,R 类是一个自动生成的类,它包含了应用程序中所有资源的标识符,如布局文件、字符串、图像和样式等。这些资源在编译时被打包到 APK 文件中,并在运行时通过 R 类来访问它们。R 类的命名空间与应用程序的包名相同,因此可以使用它来引用应用程序中的所有资源。
R 类的结构如下:
```
public final class R {
public static final class anim {
public static final int slide_in_left = 0x7f040000;
public static final int slide_out_right = 0x7f040001;
}
public static final class drawable {
public static final int ic_launcher = 0x7f020000;
public static final int logo = 0x7f020001;
}
public static final class layout {
public static final int activity_main = 0x7f030000;
public static final int list_item = 0x7f030001;
}
public static final class string {
public static final int app_name = 0x7f050000;
public static final int hello_world = 0x7f050001;
}
public static final class style {
public static final int AppTheme = 0x7f060000;
}
}
```
在这个示例中,R 类包含了四个内部类:`anim`、`drawable`、`layout` 和 `string`。每个内部类都包含了应用程序中相应类型资源的标识符。例如,`R.drawable` 内部类包含了应用程序中所有 drawable 类型资源的标识符。标识符是一个整数值,它是由编译器根据资源名称自动生成的。
在应用程序中,可以使用 R 类来访问资源。例如,要在应用程序中设置一个 ImageView 的图像,可以使用以下代码:
```
ImageView imageView = (ImageView) findViewById(R.id.image_view);
imageView.setImageResource(R.drawable.logo);
```
在这个示例中,`R.drawable.logo` 表示应用程序中 drawable 类型资源 `logo` 的标识符。通过调用 `setImageResource()` 方法并传递该标识符,可以将该资源设置为 ImageView 的图像。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)