Can setClipBounds be called on a view before it has been drawn?
I am building a custom compound control. One of the components of this
compound control is a customized button. My ShiftingTabButton is a nested
class in my compound control class.
I need to set the ShiftingTabButton's clipBounds to be slightly shorter
than the actual height when it is first drawn.
In the ShiftingTabButton's constructor shown below, I set up a few of the
necessary parameters and then call measure() with mode UNSPECIFIED, to
determine the intended size of the new view. When I run this in debug
mode, I can see width = 160 and height = 64 for my Nexus 7.
All good so far.
But when I try to call setClipBounds() with my revised clipBounds, the app
crashes. Why is this?
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!
}
I suppose I could define a useShorterClipBounds flag in the constructor
and move the setting of the clipBounds to the onDraw() method and make it
dependent on a flag check. Would this be the best approach?
No comments:
Post a Comment