layout引用getdrawable()
时间: 2023-10-06 13:10:58 浏览: 42
在Android的layout文件中,您可以使用"@drawable/xxx"资源引用语法来指定一个Drawable资源。例如,以下代码将ImageView的src属性设置为名为"my_drawable"的Drawable资源:
```
<ImageView
android:id="@+id/my_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_drawable" />
```
在这个例子中,系统会自动使用getResources().getDrawable()方法获取Drawable对象,并将其设置为ImageView的src属性。如果您想在layout文件中使用不同的Drawable资源,只需将"@drawable/xxx"更改为所需的资源名称即可。
请注意,如果您的应用程序需要与较旧版本的Android兼容,则应使用ContextCompat.getDrawable()或ViewCompat.getDrawable()方法。例如,以下代码将使用ContextCompat.getDrawable()方法为ImageView指定一个Drawable资源:
```
<ImageView
android:id="@+id/my_imageview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/my_drawable_compat" />
```
这里的"@drawable/my_drawable_compat"是一个与"@drawable/my_drawable"相同的Drawable资源,但是它是在Java代码中使用ContextCompat.getDrawable()方法获取的。这样,您就可以确保在所有版本的Android上都有一致的行为。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)