我是 Android 开发新手,在使用 BitmapFactory.decodeResource() 方法到实用程序类(不是 Activity 类的类)中时发现一些问题。
所以我正在对我的代码进行一些重构,我必须移动此代码行:
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.chef_hat_ok);
从 Activity 类方法到我在实用程序类中声明的方法。
它在 Activity 类中运行良好,但将其移动到实用程序类方法中,如下所示:
public class ImgUtility {
public Bitmap createRankingImg(int difficulty) {
// Create a Bitmap image starting from the star.png into the "/res/drawable/" directory:
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.chef_hat_ok);
return myBitmap;
}
}
我在 getResources() 方法上收到一条 IDE 错误消息,IDE 表示:
Cannot resolve method 'getResources()'
我认为发生这种情况是因为 getResources() 方法检索与 Activity 类相关的内容。
查看旧代码,我可以看到 getResources() 方法返回一个 ContextThemeWrapper 对象。我尝试在 AppCompatActivity 类中搜索(因为我原来的 Activity 扩展了它),但找不到。
所以我的疑问是:
主要问题是:如何在之前的 ImgUtility 类中正确使用 BitmapFactory.decodeResource() 方法?
为什么当我使用 BitmapFactory.decodeResource() 方法时,它会采用 ContextThemeWrapper 对象(由 getResources() 返回)方法)作为参数?这个对象到底代表什么?它与 Activity 类(class)或其他什么有关吗?在哪里声明的?
最佳答案
getResources()
方法在 Context
中可用。您可以在 Utility 类中简单地执行此操作:
public class ImgUtility {
public Bitmap createRankingImg(Context context, int difficulty) {
// Create a Bitmap image starting from the star.png into the "/res/drawable/" directory:
Bitmap myBitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.chef_hat_ok);
return myBitmap;
}
}
要回答你的第二个问题,请参阅以下内容:
java.lang.Object
↳ android.content.Context
↳ android.content.ContextWrapper
↳ android.view.ContextThemeWrapper
↳ android.app.Activity
getResources()
方法实际上存在于 Context 中类(class)。所有继承的类也都有 getResources()
方法。因此,当您从 Activity(Context 的子类)调用 getResources() 时,它很容易被调用。
关于java - 为什么我不能在实用程序类(不是 Activity 的类)中使用 BitmapFactory.decodeResource() 方法?无法解析方法 getResources(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38952777/