Android getResource() 未定义错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3663803/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 11:14:35  来源:igfitidea点击:

Android getResource() undefined error

android

提问by Jovan

I want to draw bitmap on draw method in MyPositionOverlay extends Overlay class but I get this error: The method getResource() is undefined for the type MyPositionOverlay

我想在 MyPositionOverlay extends Overlay 类中的 draw 方法上绘制位图,但出现此错误:方法 getResource() 未定义为 MyPositionOverlay 类型

Where I'm wrong?

我错在哪里?

Here is code form draw method:

这是代码形式的绘制方法:

  Bitmap bmp = BitmapFactory.decodeResource(getResource(), R.drawable.icon); 
     canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);

Thanks

谢谢

回答by Frank

The getResources() method is not a member of the Overlay class. getResources() is a member of the Context class. You need to pass a reference of a Context to your Overlay subclass so that it can load the Drawable resource:

getResources() 方法不是 Overlay 类的成员。getResources() 是 Context 类的成员。您需要将 Context 的引用传递给 Overlay 子类,以便它可以加载 Drawable 资源:

Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.icon); 

You also don't want to load a bitmap in your draw method as it is very memory intensive and will slow down your application, you should save a member variable of the bitmap in the constructor of the overlay so that it only gets loaded once.

您也不希望在 draw 方法中加载位图,因为它非常占用内存并且会减慢您的应用程序的速度,您应该在叠加层的构造函数中保存位图的成员变量,以便它只加载一次。

回答by Jorgesys

use

   Bitmap bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.icon); 

or

或者

Bitmap bmp = BitmapFactory.decodeResource(Context.getResources(), R.drawable.icon);