我正在构建一个自定义复合控件。该复合控件的一个组件是自定义按钮。我的ShiftingTabButton是我的复合控件类中的嵌套类。
我需要将ShiftingTabButton的clipBounds设置为略短于首次绘制时的实际高度。
在下面显示的ShiftingTabButton构造函数中,我设置了一些必要的参数,然后使用 measure()
模式调用 UNSPECIFIED
,确定新视图的预期大小。当我在调试模式下运行时,我可以看到我的Nexus 7的 width
= 160和 height
= 64.
到目前为止一切都很好。
但是当我尝试使用修改后的clipBounds调用setClipBounds()时,应用程序崩溃了。
我尝试在构造函数中定义 useShorterClipBounds
标记,将 clipBounds
的设置移至 {{ 1}} 方法并使其依赖于标志检查,但我仍然遇到同样的崩溃。
onDraw()
答案 0 :(得分:8)
您可以轻松地复制实现以支持旧版本:
private Rect mClipBounds;
@Override
public void draw(Canvas canvas) {
// Clip bounds implementation for JB_MR1 and older
// Does not save the canvas, because the View implementation also doesn't...
if (mClipBounds != null) {
canvas.clipRect(mClipBounds);
}
super.draw(canvas);
}
@Override
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public void setClipBounds(Rect clipBounds) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
super.setClipBounds(clipBounds);
return;
}
if (clipBounds != null) {
if (clipBounds.equals(mClipBounds)) {
return;
}
if (mClipBounds == null) {
invalidate();
mClipBounds = new Rect(clipBounds);
} else {
invalidate(Math.min(mClipBounds.left, clipBounds.left),
Math.min(mClipBounds.top, clipBounds.top),
Math.max(mClipBounds.right, clipBounds.right),
Math.max(mClipBounds.bottom, clipBounds.bottom));
mClipBounds.set(clipBounds);
}
} else {
if (mClipBounds != null) {
invalidate();
mClipBounds = null;
}
}
}
@Override
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2)
public Rect getClipBounds() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
return super.getClipBounds();
} else {
return (mClipBounds != null) ? new Rect(mClipBounds) : null;
}
}
答案 1 :(得分:2)
我发现setClipBounds()仅添加到版本4.3 r2.1中的sdk,而Nexus 7运行4.2.2,因此无法找到该方法。
相反,裁剪应该直接在onDraw()方法的画布上完成。