Android Custom View four: Custom onmeasure force Display as Square

Source: Internet
Author: User

This series is written by foreigners, dry goods! Translate out to study together. If something is wrong, don't hesitate to enlighten me!

    1. Android Custom View one: Extend existing views, add new XML attributes
    2. Android Custom View II: How to draw content
    3. Android Custom View three: Add "smooth" animations to custom views
    4. Android Custom View four: Custom onmeasure force Display as Square


The effect of the previous post-development is as follows. But looking at this picture, it's important not to notice what our custom view shows, but the size and position of the view. You will see that the line chart has a specific size (size). How is this size set? Now the code is used in a vertical direction LinearLayout , the line chart and his use of the following TextView layout_weight attributes split the height of their location LinearLayout . So what happens if we delete TextView all of them and layout_weight set the height of the line chart wrap_content ?

Yes, the whole picture becomes this after the above changes. Although the use wrap_content of the height, but the effect is to fill the whole LinearLayout . This is the default layout behavior for view, but what if we want to change it?

Layout of view

The custom view is displayed on the screen altogether in three steps: Measure (measurement), layout, Draw (draw). Basically a custom view calculates the size of this step, and then passes getMeasureWidth and getMeasureHeight gets the width and height of the view. In the layout to calculate the upper and lower left and right coordinates of this custom view, as well as the actual width and height, the view is plotted on the screen based on the data call method obtained from the layout step above onDraw .

So to modify the size, that is, to modify the default behavior in the custom view, the override onMeasure() method is required. The general general practice is to:

Override Fun Onmeasure (Widthmeasurespec:int, Heightmeasurespec:int) {super.onmeasure (Widthmeasurespec, HeightMeasur ESPEC) var widthspecmode = Measurespec.getmode (widthmeasurespec) var widthspecsize = Measurespec.getsize (WidthMeasur ESPEC) var heightspecmode = Measurespec.getmode (heightmeasurespec) var heightspecsize = Measurespec.getsize (heightMe ASURESPEC) if (Widthspecmode = = Measurespec.at_most && Heightspecmode = = measurespec.at_most) {//Set defaultWidth andHeightValuesYou defined Setmeasureddimension (Mdefaultwidth, Mdefaultheight)}Else if(Widthspecmode = = measurespec.at_most) {        //Set defaultWidthvalue  andCalculated' Heightspecsize '  asHeight setmeasureddimension (mdefaultwidth, Heightspecsize)}Else if(Heightspecmode = = measurespec.at_most) {        //SetCalculated' Widthspecsize '  asWidth and defaultHeight setmeasureddimension (widthspecsize, Mdefaultheight)}}

The simple understanding MeasureSpec.AT_MOST is that you give the line chart layout_width or layout_height set, the wrap_content system does not know the exact width, the height of the time of a mark. If there is a specific 50dp, 100dp , the value of this tag is MeasureSpec.EXACTLY . Generally, the width and height of a view are the only two types of markers.
The width and height measurements of the view are handled in three different cases:
1. AT_MOST width and height are set to the default values when the width and height are all.
2. When the width is AT_MOST not high, the width is set to the default value, and the height is set to the measured value heightSpecSize .
3. The width is the exact value, AT_MOST the height is the time, the width is set widthSpecSize , the height is set to the default value.

And here we are, surprisingly simple. Because you want to set as a square, you can use the relatively small value in width and height as a common value for width and height:

override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {    super.onMeasure(widthMeasureSpec, heightMeasureSpec)    var0    var width = getMeasuredWidth()    var height = getMeasuredHeight()    if (width > height) {        size = height    else {        size = width    }    setMeasuredDimension(size, size)}

As we said earlier, we want to set the custom view of the line chart to square. So, regardless of the mode of measurement, as long as the width, high school minimum value can be.

而上面说到的layout部分,对于有子view的`View`比较有用,也就是说对于继承自`ViewGroup`的`View`来说比较有用。我们的折线图知识一个单纯的不能更单纯的`View`。

We are not available in the onDraw method and in the getWidth() method before getHeight() onMeasure() . Because this time is calculating the width, the height. In this method you can only fetch getMeasuredWidth() and getMeasuredHeight() .

Override onMeasure Method must be called at the end of the setMeasuredDimension method. The call setMeasuredDimension method is to tell the parent view How much the current view is measured. If you do not call this method, you will throw an exception.

The layout, width match_parent , and height after the modification wrap_content . Unnecessary attributes have been omitted .

<relativelayout>    <linearlayout>        <button android:text="Walking" />        <button android:text="Running" />        <button android:text="cycling" />    </linearlayout>    <demo.customview.customviewdemo.Views.SquareLineChartViewandroid:layout_width=" Match_parent "android:layout_height=" wrap_content " />                </relativelayout>

Effect:

Supports any width-height ratio

A square view is very useful. For example, ImageView after inheriting the same as above, override The onMeasure() method to get a view that has always been a square display. So, since we have supported the width and height of 1:1, why not support any aspect ratio.

OverrideFun Onmeasure (Widthmeasurespec:int, Heightmeasurespec:int) {Super. Onmeasure (Widthmeasurespec, Heightmeasurespec)varwidth = getmeasuredwidth ()varHeight = getmeasuredheight ()varwidthwithoutpadding = Width-paddingleft-paddingrightvarheightwithoutpadding = Height-paddingtop-paddingbottomvarMaxWidth = (heightwithoutpadding * RATIO). ToInt ()varMaxHeight = (widthwithoutpadding/ratio). ToInt ()if(Widthwithoutpadding > MaxWidth) {width = maxWidth + paddingleft + paddingright}Else{height = maxheight + paddingtop + paddingbottom} setmeasureddimension (width, height)}

The above code can support any aspect ratio. Look at the effect (scale 7:3):

Android Custom View four: Custom onmeasure force Display as Square

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.