有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java我一直收到一个错误,说“无法从int转换为Drawable”。我正在尝试将图像分配到位置。有办法解决这个问题吗?

我似乎无法在drawable文件夹中引用我的图像。我有图像,但我不断得到一个错误,说明我不能转换一个int到Drawable。我的R.java生成的文件中有图像的字符串,但是它被设置为“publicstaticfinalintrestaurant=0x7f020001;”

package com.CS3040.Places;

import 安卓.content.Context;
import 安卓.graphics.BitmapFactory;
import 安卓.graphics.drawable.Drawable;
import com.CS3040.*;
import com.CS3040.Coursework.R;

import com.google.安卓.maps.GeoPoint;
import com.google.安卓.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;
    }
}

共 (3) 个答案

  1. # 1 楼答案

    我想你想要这样的东西:

    Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.restaurant);
    this.marker = bitmap;
    

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

    marker = getResources().getDrawable(R.drawable.restaurant);
    
  2. # 2 楼答案

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

  3. # 3 楼答案

    您需要执行以下操作:

    marker = getResources().getDrawable(R.drawable.restaurant);
    

    获取消息“类型PlaceOverlayItem的方法getResources()未定义”的原因是getResources()是从上下文类继承的方法,因此必须从活动(或其他)调用它,或将上下文传递给方法

    希望这有帮助