我一直收到错误,说"无法从int转换为Drawable".我正在尝试将图像分配给地方.有办法解决这个问题吗?

use*_*217 6 java android overlay drawable

我似乎无法在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;
    }
}
Run Code Online (Sandbox Code Playgroud)

小智 18

您需要执行以下操作:

marker = getResources().getDrawable(R.drawable.restaurant);
Run Code Online (Sandbox Code Playgroud)

您收到消息"方法getResources()未定义PlaceOverlayItem类型"的原因是因为getResources()是从Context类继承的方法,因此您必须从Activity(或左右)调用它或将上下文传递给你的方法.

希望这可以帮助

  • 截至今天,不推荐使用getDrawable. (2认同)

Spa*_*rky 7

我想你想要这样的东西:

Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.restaurant);
this.marker = bitmap;
Run Code Online (Sandbox Code Playgroud)

或者,使用您的解决方案:

marker = getResources().getDrawable(R.drawable.restaurant);
Run Code Online (Sandbox Code Playgroud)


MBy*_*ByD 0

R.drawable.restaurant是一个常量 int ,它保存了可绘制资源resturant的id ,它不是一个可绘制对象。