是否可以设置 ImageView 以便仅在某些情况下调用 onDraw?

Can an ImageView be set up so that onDraw is only called in certain cases?

我的应用需要显示一组图像。有些图像是内置的,而另一些则是由用户添加的。我为此创建了一个 class,称为 SymbolBox(我在此处对其进行了简化):

public class SymbolBox extends android.support.v7.widget.AppCompatImageView {

 private FullSymbol  mSymbol; // Symbol to show                 
 private final Paint mPaint;  // Paint variable to use

 // Constructor initialises options and sets up the paint object
 public SymbolBox(Context context, AttributeSet attrs) {
        super(context, attrs);

        mPaint          = new Paint();

 }

 // Set the symbol
 public void setSymbol(FullSymbol symbol) { 
    this.mSymbol = symbol; 
 }

 // Draw the symbol
 protected void onDraw(Canvas canvas) {

   if(this.mSymbol == null) return;
   String drawableUrl  = mSymbol.getUrl();
   if(drawableUrl != null) return;  // Only use this to draw from base

   // Get canvas size
   float height = getHeight();
   float width  = getWidth();

   // Draw the symbol
   String drawableName = mSymbol.getBase();
   Context context = getContext();


     if((drawableName == null) || (drawableName.equals(""))) { drawableName = "blank"; }

     Resources resources = context.getResources();
     final int resourceId = resources.getIdentifier(drawableName,
                    "drawable",
                    context.getPackageName());

     Drawable d;
     if (resourceId != 0) {
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
         d = resources.getDrawable(resourceId, context.getTheme());
       } else {
         d = resources.getDrawable(resourceId);
       }
       d.setBounds(0, 0, getWidth(), getHeight());
       d.draw(canvas);
     }
}

FullSymbol 定义如下:

public class FullSymbol {

    private String  name, base;
    private String  url;

    // CONSTRUCTOR
    public FullSymbol() {}

    public String getBase() { return this.base; }
    public String getName() { return name; }
    public String getUrl() { return url; }

    public void setBase(String newBase) { this.base = newBase; }
    public void setName(String newName) { this.name = newName; }
    public void setUrl(String newUrl)   { this.url = newUrl; }
}

每个 FullSymbol 可以有一个 base 或一个 url(如果两者都没有,则基数将设置为 "blank")。 base 是对内置图像的引用; url 是对在线图片的引用(已由用户上传)。

在调用所有这些的片段中,我在布局中设置了一个 SymbolBox,然后使用 Glide 将图像加载到 SymbolBox(我下载上传的图片时遇到问题,所以现在只使用固定的 url):

SymbolBox test = rootView.findViewById(R.id.testSymbol);
Glide.with(this).load("http://path/to/image").into(test);

因此,如果 FullSymbol 有一个 url,那么 url 处的图像应该使用 Glide 加载到 SymbolBox 中。如果没有url,则使用base的值,使用drawables绘制图像。

我遇到的问题是,如果从 SymbolBox class 中取出 onDraw,Glide 部分只会显示任何内容(即完全注释掉;如果我只有一个空函数,它就不起作用).但是如果没有 url 并且我正在使用 base.

我需要 onDraw 来绘制图像

如果 url 存在,有没有办法以某种方式忽略 onDraw,但在其他情况下包括它?或者以不同的方式从基础中提取 - 我可以创建一个函数,但我需要访问 Canvas。我该如何解决这个问题?

我设法解决了这个问题 - 我在 SymbolBox 中添加了对 onDrawsuper 方法的调用:

protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

   ... rest of the code stayed the same ...

}

它奏效了。