Android从不同的类获取资源
我有两个类,A类称为Apply,B类称为Option 我希望类A从类B获取资源,但我得到了一个错误 我犯的错误Android从不同的类获取资源,android,resources,bitmap,Android,Resources,Bitmap,我有两个类,A类称为Apply,B类称为Option 我希望类A从类B获取资源,但我得到了一个错误 我犯的错误 Cannot make a static reference to the non-static method getResources() from the type ContextWrapper 类上的函数 public static void applyBitmap(int resourceID) { BitmapFactory.Options opt = new Bi
Cannot make a static reference to the non-static method getResources() from the type ContextWrapper
类上的函数
public static void applyBitmap(int resourceID) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inScaled = true;
opt.inPurgeable = true;
opt.inInputShareable = true;
Bitmap brightBitmap = BitmapFactory.decodeResource(getResources(), resourceID, opt);
brightBitmap = Bitmap.createScaledBitmap(brightBitmap, 100, 100, false);
MyBitmap = brightBitmap;
}
以及类B中的资源按钮示例
// the 34th button
Button tf = (Button) findViewById(R.id.tFour);
tf.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Apply.applyBitmap(R.drawable.tFour);
}
});
注*:以前,当函数在中的类B上时工作得很好,但是我知道我认为我需要静态资源,但是如何?我不知道
我尝试了
Option.getResources()
,但它不起作用,它给出了一个错误您在访问getResources()
时没有引用上下文。因为这是一个静态方法,所以您只能访问该类中的其他静态方法,而不提供引用
相反,您必须将上下文作为参数传递:
// the 34th button
Button tf = (Button) findViewById(R.id.tFour);
tf.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Apply.applyBitmap(v.getContext(), R.drawable.tFour); // Pass your context to the static method
}
});
然后,您必须为getResources()
引用它:
如果你从A类中删除“静态”怎么办?你需要它吗?实际上,这是对java的基本理解。我谦虚地建议您重新阅读java基础知识
public static void applyBitmap(Context context, int resourceID) {
BitmapFactory.Options opt = new BitmapFactory.Options();
opt.inScaled = true;
opt.inPurgeable = true;
opt.inInputShareable = true;
Bitmap brightBitmap = BitmapFactory.decodeResource(context.getResources(), resourceID, opt); // Use the passed context to access resources
brightBitmap = Bitmap.createScaledBitmap(brightBitmap, 100, 100, false);
MyBitmap = brightBitmap;
}