Android : Implementing custom view with buttons
I am creating a custom view which will have a bitmap so that user can draw in it and some normal Android buttons in the bottom for user interaction.
To size my bitmap (height of drawing areas should be 50% ) I am overriding
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
this.setMeasuredDimension(widthMeasureSpec, (int)(parentHeight * 0.50));
super.onMeasure(widthMeasureSpec, (int)(parentHeight * 0.50));
}
This gives me exception that "java.lang.IllegalArgumentException: width and height must be > 0"
If I set super.onMeasure(widthMeasureSpec, heightMeasureSpec); I cannot see my buttons places in the bottom.
If I dont write super.onMeasure() anything I draw is not seen once I release the mouse.
I am using a xml file for layout :
<view class="com.my.CustomView" android:id="@+id/myView"
android:layout_width="fill_parent" android:layout_height="wrap_content"/>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content" android:orientation="horizontal">
<Button a开发者_运维知识库ndroid:layout_height="wrap_content"
android:text="B1" android:layout_width="wrap_content"/>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content" android:text="B2"/>
</LinearLayout>
What else should I do ?
Wouldn't be easier to give your custom view a size in dp. You then can see your layout in design mode. Then use onSizeChanged to find out the size of your canvas.
onMeasure is usually used when the size of the canvas depends on runtime values, like the result of a game or number of loaded items etc.
Here is an example that works:
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
int newH = (int) (parentHeight / 1.5f);
this.setMeasuredDimension(parentWidth, newH );
}
Also the constructor for your custom vuew must include attribute set:
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}
Your onMeasure()
is incomplete, it should take into account also the mode (UNSPECIFIED
, EXACTLY
, AT_MOST
). Docs say that onMeasure()
might get called several times, even with UNSPECIFIED 0-0 sizes, to see what size the view would like to be. See View, section Layout. There's no need to call super.onMeasure()
.
I don't get if your custom view includes only the drawing area or you're inflating the buttons too in it (my guess is the first case), but try Hierarchy Viewer, it will help you to understand how views are being laid out (and hence why in some cases you see drawings and sometimes not).
精彩评论