Java 我一直收到一条错误消息,说“无法从 int 转换为 Drawable”。我正在尝试将图像分配给地点。有没有办法解决这个问题?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9711138/
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
I keep getting an error saying "cannot convert from int to Drawable". I'm trying to assign an image to places. Is there a way of working around this?
提问by user1270217
I can't seem to reference my image in the drawable folder. I have the image there however i keep getting an error stating that I cannot convert an int to Drawable. my R.java generated file has the string in there for the image however it is set as "public static final int restaurant=0x7f020001;"
我似乎无法在 drawable 文件夹中引用我的图像。我在那里有图像,但是我不断收到错误消息,指出我无法将 int 转换为 Drawable。我的 R.java 生成的文件中有图像的字符串,但它被设置为“public static final int restaurant=0x7f020001;”
package com.CS3040.Places;
import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import com.CS3040.*;
import com.CS3040.Coursework.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.OverlayItem;
public class PlaceOverlayItem extends OverlayItem {
private final GeoPoint point;
private final Place place;
private final Drawable marker;
public PlaceOverlayItem(Place p, String type) {
super(p.getGeoPoint(), p.getName(), p.getFormatted_address());
if(type.equals("restaurant")){ this.marker = R.drawable.restaurant; }
//super.setMarker(this.marker);
this.point = p.getGeoPoint();
this.place = p;
}
/**
* @return the point
*/
public GeoPoint getPoint() {
return point;
}
/**
* @return the place
*/
public Place getPlace() {
return place;
}
}
回答by MByD
R.drawable.restaurant
is a constant int which holds the id of the drawable resource resturant, it is not a Drawable object.
R.drawable.restaurant
是一个常数INT其保持绘制资源的id RESTURANT,它不是一个可绘制对象。
回答by Sparky
I think you want something like this:
我想你想要这样的东西:
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.restaurant);
this.marker = bitmap;
Or, using your solution:
或者,使用您的解决方案:
marker = getResources().getDrawable(R.drawable.restaurant);
回答by Zadec
You need to do as follows:
您需要执行以下操作:
marker = getResources().getDrawable(R.drawable.restaurant);
The reason you get the message "The method getResources() is undefined for the type PlaceOverlayItem" is because getResources() is a method inherited from Context class, so you got to call it from an Activity (or so) or pass the context to your method.
您收到消息“方法 getResources() 对于 PlaceOverlayItem 类型未定义”的原因是因为 getResources() 是从 Context 类继承的方法,因此您必须从 Activity(左右)调用它或将上下文传递给你的方法。
Hope this helps
希望这可以帮助