Sou*_*ion 3 android android-custom-view
我正在构建一个自定义复合控件.该复合控件的一个组件是自定义按钮.我的ShiftingTabButton是我的复合控件类中的嵌套类.
我需要将ShiftingTabButton的clipBounds设置为略短于首次绘制时的实际高度.
在下面显示的ShiftingTabButton构造函数中,我设置了一些必要的参数,然后measure()使用mode 调用UNSPECIFIED,以确定新视图的预期大小.当我在调试模式下运行时,我可以看到width= 160和height= 64我的Nexus 7.
到目前为止都很好.
但是当我尝试使用修改后的clipBounds调用setClipBounds()时,应用程序崩溃了.
我已经尝试useShorterClipBounds在构造函数中定义一个标志,将方法的设置移动clipBounds到onDraw()方法并使其依赖于标志检查,但我仍然得到同样的崩溃.
public ShiftingTabButton(Context context, String string) {
super(context);
// parameter setup
this.setText(string);
this.setBackground(getResources().getDrawable(R.drawable.tab_unselected));
this.setId(generateChildViewId());
this.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
this.setPadding(dpToPx(7), 0, dpToPx(7), 0);
// measure the view
int widthMeasureSpec = MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, MeasureSpec.UNSPECIFIED);
int heightMeasureSpec = MeasureSpec.makeMeasureSpec(ViewGroup.LayoutParams.WRAP_CONTENT, MeasureSpec.UNSPECIFIED);
this.measure(widthMeasureSpec, heightMeasureSpec);
int width = this.getMeasuredWidth();
int height = this.getMeasuredHeight();
// adjust the clipBounds
Rect clipBounds = new Rect();
clipBounds.set(0, 0, width, height - dpToPx(16));
this.setClipBounds(clipBounds); // !App crashes executing this line of code!
}
Run Code Online (Sandbox Code Playgroud)
您可以轻松地复制实现以支持旧版本:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5141 次 |
| 最近记录: |