Android - 以编程方式使用@android:drawable/AnImage 设置图像

Android - set an image using @android:drawable/AnImage programmatically

我知道如何使用 @drawable 但如何在代码中设置 @android:drawable/ic_image

在XML中,它将是

android:icon="@drawable/my_image"

android:icon="@mipmap/my_image"

对于android:drawable,它将是:

android:icon="@android:drawable/ic_menu_delete"

但是最新的代码怎么设置图片呢?

我应该使用哪个?

你可以像下面的代码那样做:

img.setImageDrawable(getResources().getDrawable(R.drawable.ic_image, null));

要使用 Android 资源,您应该在资源名称中使用“android.R”前缀。这是代码示例:

    view.setBackgroundResource(android.R.drawable.ic_menu_delete);

这会帮助你。不要使用 getResource().getDrawable()。它已被弃用。

所以基本上:

 Drawable drawable = ContextCompat.getDrawable(this, R.drawable.your_drawable);
    img.setBackgroundDrawable(drawable);

对于 android 个可绘制对象,您执行以下操作:

ContextCompat.getDrawable(this, android.R.drawable.your_drawable);

对于 Mipmap:

ContextCompat.getDrawable(this, R.mipmap.your_drawable);