在 Drawable 中使用 onSizeChanged class

Using onSizeChanged in Drawable class

我创建了一个扩展 Drawable 的自定义 class。我正在尝试使用 onSizeChanged() 获取 Drawable 的尺寸,如下所示

public class Circle extends Drawable {
    ...
    @Override
    protected void onSizeChanged(int xNew, int yNew, int xOld, int yOld) {
        super.onSizeChanged(xNew, yNew, xOld, yOld);
    }
}

但是我收到一条错误消息 "Method does not override from the superclass"。我该怎么做才能解决它?


非常感谢 Michael Spitsin 的回答。要获取可绘制对象所附加的布局的尺寸,请使用以下代码

@Override
protected void onBoundsChange(Rect bounds) {
    mHeight = bounds.height();
    mWidth = bounds.width();
}

如果我们转到视图 source code and in Drawable source code,我们将看到以下内容:

在 View.setBackgroundDrawable(Drawable) 中,如果我们传递的不是空值,那么 mBackground 字段(负责存储背景可绘制对象)将被更新。

如果我们尝试查找方法 Drawable.onBoundsChanged() 的用法,那么我们会发现它主要用于 Drawable.setBounds 方法。如果我们找到它的用法,我们将在 View.class:

中看到下一个片段
private void drawBackground(Canvas canvas) {
    final Drawable background = mBackground;
    if (background == null) {
        return;
    }

    if (mBackgroundSizeChanged) {
        background.setBounds(0, 0,  mRight - mLeft, mBottom - mTop);
        mBackgroundSizeChanged = false;
       rebuildOutline();
    }

    //draw background through background.draw(canvas)
}

因此,您的任务可以使用 onBoundsChanged 回调。