And*_*ili 0 java android bitmapfactory android-activity android-resources
我在Android开发中绝对是新的,我发现使用BitmapFactory.decodeResource()方法进入实用程序类(不是活动类的类)的问题.
所以我正在对我的代码进行一些重构,我必须移动这个代码行:
Bitmap myBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.chef_hat_ok);
Run Code Online (Sandbox Code Playgroud)
从活动类方法到我在实用程序类中声明的方法.
它在活动类中运行良好,但将int移入实用程序类方法,如下所示:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
我在getResources()方法上获取了一条IDE错误消息,IDE对我说:
无法解析方法'getResources()'
我认为这是因为getResources()方法检索与活动类相关的内容.
查看旧代码,我可以看到getResources()方法返回一个ContextThemeWrapper对象.我试图在AppCompatActivity类中搜索(因为我的原始活动扩展了它),但我找不到.
所以我的怀疑是:
1)主要问题是:如何在我的previus ImgUtility clas中正确使用BitmapFactory.decodeResource()方法?
2)为什么当我使用BitmapFactory.decodeResource()方法时,它将ContextThemeWrapper对象(由getResources()方法返回)作为参数?究竟什么代表了这个对象?它与活动类有什么关系?在哪里申报?
TNX
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;
}
}
Run Code Online (Sandbox Code Playgroud)
要回答第二个问题,请看:
java.lang.Object
? android.content.Context
? android.content.ContextWrapper
? android.view.ContextThemeWrapper
? android.app.Activity
Run Code Online (Sandbox Code Playgroud)
该getResources()
方法实际上存在于Context类中.所有固有的类也都有这种getResources()
方法.因此,当您getResources()
从Activity(它是Context的子类)调用时,它很容易被调用.