ContextCompat.getDrawable()
方法用于从资源中获取 Drawable 对象。这个方法需要两个参数:一个是 Context
对象,另一个是 Drawable 资源的 ID。
Context
是一个抽象类,它提供了访问应用程序特定资源和类的接口。它通常用于加载资源、启动活动、发送广播等。上下文参数通常是你当前的 Activity 或者 Application 对象。这是因为这些对象都继承自 Context
类,并且它们包含了访问应用程序资源所需的信息。
以下是一些使用 ContextCompat.getDrawable()
的示例:
Activity activity = this; // 'this' 指向当前的 Activity
Drawable drawable = ContextCompat.getDrawable(activity, R.drawable.your_drawable);
如果你需要在非 Activity 上下文中获取 Drawable(例如在一个 Service 或者 BroadcastReceiver 中),你可以使用 Application 的上下文:
Context context = getApplicationContext(); // 在 Activity 中获取 Application 上下文
Drawable drawable = ContextCompat.getDrawable(context, R.drawable.your_drawable);
ContextCompat.getDrawable()
方法可以确保在不同版本的 Android 系统上都能正确地加载 Drawable,尤其是在 Android 5.0(API 级别 21)及以上版本中,直接使用 getResources().getDrawable()
已经不推荐使用。ContextCompat.getDrawable()
的资源 ID 是有效的,否则会抛出 Resources.NotFoundException
。如果你在使用 ContextCompat.getDrawable()
时遇到问题,比如返回 null
或者抛出异常,可以检查以下几点:
res/drawable
)。通过以上步骤,你应该能够正确地使用 ContextCompat.getDrawable()
方法,并解决可能出现的问题。
领取专属 10元无门槛券
手把手带您无忧上云