如何从android包中的资源ID获取Drawable对象?

Bla*_*icz 145 resources android drawable android-context

我需要让Drawable对象显示在图像按钮上.有没有办法使用下面的代码(或类似的东西)从android.R.drawable.*包中获取对象?

例如,如果drawableId是android.R.drawable.ic_delete

mContext.getResources().getDrawable(drawableId)
Run Code Online (Sandbox Code Playgroud)

Pet*_*ton 206

Drawable d = getResources().getDrawable(android.R.drawable.ic_dialog_email);
ImageView image = (ImageView)findViewById(R.id.image);
image.setImageDrawable(d);
Run Code Online (Sandbox Code Playgroud)

  • 从API 22开始.不推荐使用`getDrawable(int id)`.请改用`getDrawable(int id,Resources.Theme theme)`.方法`getTheme()`应该会有所帮助. (17认同)

Muh*_*man 104

API 21开始,您应该使用该getDrawable(int, Theme)方法而不是getDrawable(int),因为它允许您获取drawableresource ID给定的特定对象关联的对象screen density/theme.调用该deprecated getDrawable(int)方法相当于调用getDrawable(int, null).

您应该使用支持库中的以下代码:

ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)
Run Code Online (Sandbox Code Playgroud)

使用此方法相当于调用:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    return resources.getDrawable(id, context.getTheme());
} else {
    return resources.getDrawable(id);
}
Run Code Online (Sandbox Code Playgroud)


小智 9

从API 21开始,您还可以使用:

   ResourcesCompat.getDrawable(getResources(), R.drawable.name, null);
Run Code Online (Sandbox Code Playgroud)

代替 ContextCompat.getDrawable(context, android.R.drawable.ic_dialog_email)

  • 您能为选择提供进一步的解释吗 (2认同)

San*_*inh 8

从 API 21 开始,“getDrawable(int id)”已弃用

所以现在你需要使用

ResourcesCompat.getDrawable(context.getResources(), R.drawable.img_user, null)
Run Code Online (Sandbox Code Playgroud)

但最好的方法是:

- 您应该创建一个公共类来获取可绘制对象和颜色,因为如果将来有任何弃用,那么您无需在项目中的任何地方进行更改。您只需在此方法中进行更改
import android.content.Context
import android.graphics.drawable.Drawable
import androidx.core.content.res.ResourcesCompat

object ResourceUtils {
    fun getColor(context: Context, color: Int): Int {
        return ResourcesCompat.getColor(context.resources, color, null)
    }

    fun getDrawable(context: Context, drawable: Int): Drawable? {
        return ResourcesCompat.getDrawable(context.resources, drawable, null)
    }
}
Run Code Online (Sandbox Code Playgroud)

使用这种方法,例如:

Drawable img=ResourceUtils.getDrawable(context, R.drawable.img_user)
image.setImageDrawable(img);
Run Code Online (Sandbox Code Playgroud)


Inz*_* IT 5

最好的办法是

 button.setBackgroundResource(android.R.drawable.ic_delete);
Run Code Online (Sandbox Code Playgroud)

或者使用以下代码绘制可绘制左、上、右、下。在这种情况下我设置了drawable left。

int imgResource = R.drawable.left_img;
button.setCompoundDrawablesWithIntrinsicBounds(imgResource, 0, 0, 0);
Run Code Online (Sandbox Code Playgroud)

getResources().getDrawable()现已弃用