我正在构建一个自定义复合控件。这个复合控件的一个组件是定制的按钮。我的ShiftingTabButton是我复合控件类中的嵌套类。
我需要在第一次绘制时将ShiftingTabButton的clipBounds设置为略短于实际高度。
在下面展示的ShiftingTabButton的构造函数中,我设置了一些必要的参数,然后使用UNSPECIFIED模式调用measure()来确定新视图的预期大小。当我以调试模式运行时,可以看到对于我的Nexus 7,width=160和height=64。
目前一切正常。
但是当我尝试使用修改后的clipBounds调用setClipBounds()时,应用程序会崩溃。
我尝试在构造函数中定义一个useShorterClipBounds标志,将clipBounds的设置移动到onDraw()方法中并使其依赖于标志检查,但我仍然遇到相同的崩溃。
我需要在第一次绘制时将ShiftingTabButton的clipBounds设置为略短于实际高度。
在下面展示的ShiftingTabButton的构造函数中,我设置了一些必要的参数,然后使用UNSPECIFIED模式调用measure()来确定新视图的预期大小。当我以调试模式运行时,可以看到对于我的Nexus 7,width=160和height=64。
目前一切正常。
但是当我尝试使用修改后的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!
}