0
votes

Created Custom view and overridden it's onDraw().

  • Without Overriding onMeasure() canvas occupies the entire screen of device.
  • Overriding onMeasure(), canvas is re-sized to dimension passed to setMeasuredDimension().

Hence we can resize the canvas for sure and It has to be done in onMeasure().

I want to re-size the canvas of my custom view to the size specified in it's LayoutParams(XML or Java)

Now in need of method/attribute which will return size parameters mentioned in LayoutParams to pass inside setMeasuredDimension().

  • getWidth()/getHeight() - value is set only after first pass of onMeasure()

  • getLayoutParams().width/getLayoutParams().height - Not sure when this value will return valid values (setting params programatically gives value '-1')

  • getMeasuredWidth()/getMeasuredHeight() - returns size parameter specified in layout params only if it has been set in XML and not if is programatically assigned.

Is there any other gurantee method which will returns width & height that has been set in layout params of customview OR getMeasuredWidth()/getMeasuredHeight() is the correct choice to pass in setMeasureDimensions()?

Might be duplicate of Android Custom View Size

2
The values from the LayoutParams are sent to the onMeasure method, it's your job to override it in such way that it reflects those values. - user
@Luksprog: Is there any method to find whether "fill_parent" or "wrap_content" has been set. - Mani
@Luksprog: The values from the LayoutParams are sent to the onMeasure method only if it has been set in XML, not if it programatically assigned. CustomView customView = new CustomView(getApplicationContext()); customView.setLayoutParams(new LayoutParams(100, 100)); onMeasure() receives available screen width and height. - Mani

2 Answers

0
votes

one solution is to get the dimensions from the Activity and pass them to the View.

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

metrics.widthPixels will get you the desired width

0
votes

Credits to @Luksprog as he said. Having this info, I'm able to figure out the following:

getLayoutParams().width/getLayoutParams().height - Can contain any one of the below values

  • LayoutParams.WRAP_CONTENT(whose value is -2)
  • LayoutParams.MATCH_PARENT(whose value is -1) or
  • The width specified in the view's attribute(in XML) layout_width

getMeasuredWidth()/getMeasuredHeight()(Also i/p parameters to onMeasure()) - Will hold maximum size of this view can be occupied visibly in PIXELS.

Hence Answering my own ques: we need to add logic inside onMeasure() using these methods to restrict canvas size as answered on question linked to this post or also your own calculation to resize the canvas!