Design a FrameLayout (Kotlin) and framelayoutkotlin

Source: Internet
Author: User

Design a FrameLayout (Kotlin) and framelayoutkotlin

Split the parts and assemble the parts back and forth to familiarize yourself with the structure.

FrameLayout features sub-views are stacked to display the size of FrameLayout in the order of addition equal to the size of its largest sub-View (visible) (plus the padding value) If you want to involve the sub-View of GONE in the calculation, you need to set setMeasureAllChildren (boolean) and setConsiderGoneChildrenWhenMeasuring () to true to control the layout of sub-views through layout_gravity.

Based on the above features, I also want to implement a simple FrameLayout. How should I start?

Here, we naturally consider inheriting ViewGroup, and then rewriting the onMeasure and onLayout methods, and the onLayout method must be implemented (because this is an abstract method and must be implemented by subclass)

Measurement

Here, the measurement process is: traverse the ViewGroup, call the measure method of the sub-View for measurement, and obtain the Margin information of the sub-View through the LayoutParams of the sub-View, then, combine the measurement size and Margin value of the View to calculate the size of the ViewGroup, and set the size to the measurement size of the ViewGroup.

/** Dimensional measurement **/override fun onMeasure (widthMeasureSpec: Int, heightMeasureSpec: Int) {var maxWidth: Int = 0 var maxHeight: int = 0 // traverse the child View for (I in 0 until childCount) {val child = getChildAt (I) if (child. visibility! = View. GONE) {// call an instance method of ViewGroup (essentially the layout method of View). // because of FrameLayout, child views do not interfere with the size, so the used space is 0 // This calculation process calculates padding and margin measureChildWithMargins (child, widthMeasureSpec, 0, heightMeasureSpec, 0) var layoutParams = child. layoutParams as LayoutParams // get the maximum width and height, and consider the Sub-View's Margin maxWidth = Math. max (maxWidth, child. measuredWidth + layoutParams. leftMargin + layoutParams. rightMargin) maxHeight = Math. max (maxHeight, child. measuredHeight + layoutParams. topMargin + layoutParams. bottomMargin) // consider the padding value of FrameLayout (the effect of foreground and background on dimensions is not considered here) maxWidth + = paddingLeft + paddingRight maxHeight + = paddingTop + paddingBottom // set the size of setMeasuredDimension (resolveSize (maxWidth, widthMeasureSpec), View. resolveSize (maxHeight, heightMeasureSpec ))}}}

Note that the LayoutParams here is not the LayoutParams of the ViewGroup, because the LayoutParams in the ViewGroup does not support margin, but only supports attributes with high width, but it does not matter. There is a MarginLayoutParams in the ViewGroup class, added support for margin.

Here we plan to design a FrameLayout, so we have to support Margin and layout_gravity;

/** The child View uses LayoutParams to tell the parent View how to layout it. * {@ link android. r. styleable # ViewGroup_Layout ViewGroup Layout Attributes} contains all Attributes supported by the LayoutParams class * Including layout_width and layout_height * as the base class. LayoutParams only describes the width and height of the View. For each dimension, (Optional) MATCH_PARENT and WRAP_CONTENT *. MATCH_PARENT indicates that the child View is as large as the parent View * WRAP_CONTENT indicates that the View needs to be large enough to accommodate its content (including padding) ** different ViewGroup subclasses have different LayoutParams and Other implementations to add their own features. * For example, MarginLayoutParams in this class can be used. To add support for Margin and gravity **/class LayoutParams: MarginLayoutParams {companion object {val percent =-1} // Add gravity to support var gravity = UNSPECIFIED_GRAVITY constructor (c: Context, attrs: AttributeSet ?): Super (c, attrs) {val typedArray = c. obtainStyledAttributes (R. styleable. KFrameLayout_Layout) gravity = typedArray. getInt (R. styleable. KFrameLayout_Layout_layout_gravity, UNSPECIFIED_GRAVITY) typedArray. recycle ()} constructor (width: Int, height: Int): super (width, height) constructor (source: MarginLayoutParams ?): Super (source) constructor (source: ViewGroup. LayoutParams ?): Super (source) constructor (width: Int, height: Int, gravity: Int): super (width, height) {this. gravity = gravity} constructor (source: LayoutParams): super (source) {this. gravity = source. gravity }}

If you define your own LayoutParams in this way, and then forcibly convert the LayoutParams obtained by the sub-View to its own LayoutParams, this custom View does not work, the specific cause will be described later.

Layout

After the measurement process, we can get the measurement size and traverse the sub-View to make the corresponding layout. This mainly defines the left boundary of the sub-View and the distance between the upper boundary.

// The onLayout method of ViewGroup is an abstract method and must be implemented by sub-classes. // the core idea of this process is to traverse the sub-View and find four coordinate values for the sub-View, then, the Child View's layout method is called to override fun onLayout (changed: Boolean, l: Int, t: Int, r: Int, B: Int) {layoutChildren (l, t, r, B)} private fun layoutChildren (l: Int, t: Int, r: Int, B: Int) {val parentLeft = paddingLeft val parentRight = r-l-paddingRight val parentTop = paddingTop val parentBottom = B-t- PaddingBottom for (I in 0 until childCount) {val child = getChildAt (I) val childWidth = child. measuredWidth val childHeight = child. measuredHeight if (child. visibility! = View. GONE) {var childLeft: Int var childTop: Int val layoutParams: LayoutParams = child. layoutParams as LayoutParams var gravity = layoutParams. gravity if (gravity =-1) {gravity = LayoutParams. UNSPECIFIED_GRAVITY} // left-to-right layout, or right-to-left layout (rarely used in China) val absoluteGravity = Gravity. getAbsoluteGravity (gravity, layoutDirection) val verticalGravity = gravity and Gravity. VERTICAL_GRAVITY_MASK // horizontal childLeft = when (absoluteGravity and Gravity. HORIZONTAL_GRAVITY_MASK) {Gravity. CENTER_HORIZONTAL-> {// The concept parentLeft + layoutParams must be clarified here. rightMargin-layoutParams. leftMargin + (parentRight-parentLeft-childWidth)/2} Gravity. RIGHT-> {parentRight-layoutParams. rightMargin-childWidth} else-> {parentLeft + layoutParams. leftMargin }}// vertical childTop = when (verticalGravity) {Gravity. CENTER_VERTICAL-> {parentTop + layoutParams. bottomMargin-layoutParams. topMargin + (parentBottom-parentTop-childHeight)/2} Gravity. BOTTOM-> {parentBottom-layoutParams. bottomMargin} else-> {parentTop + layoutParams. topMargin} child. layout (childLeft, childTop, childLeft + childWidth, childTop + childHeight )}}}

This layout process must be set according to its own characteristics. For example, FrameLayout is a cascade relationship because the child views do not affect each other, because the layout relationship between the sibling views is not considered, this is much easier.

There is another difficulty here: you need to understand the true meaning of margin and padding, and the actual calculation process of left, right, and center layout in the layout.

Complete

As mentioned above, LayoutParams may be problematic if it is forced to convert directly. If there is any problem, we have to start with the View loading mechanism. I will not explain it for the time being, here we will first write out the solution, which is to rewrite several methods:

 override fun checkLayoutParams(p: ViewGroup.LayoutParams?): Boolean {        return p is LayoutParams    }    override fun generateLayoutParams(attrs: AttributeSet?): ViewGroup.LayoutParams {        return LayoutParams(context,attrs)    }    override fun generateLayoutParams(p: ViewGroup.LayoutParams?): ViewGroup.LayoutParams {        return LayoutParams(p)    }    override fun generateDefaultLayoutParams(): ViewGroup.LayoutParams {        return LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT)    }

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.