Android Advanced – custom ViewGroup – FlowLayout Streaming layout implemented in Java/Kotlin version

  • What is streaming layout
  • Train of thought
  • Margin cannot be obtained in ViewGroup

What is streaming layout

Train of thought

  • Step 1: In onMeasure(), you need to measure the width and height of each child View and store it as a View
  • Step 2: Use a variable to record the width and height of each view and record it
  • Step 3: If the width of each record + current width = ViewGroup width, newline is required
  • Step 4: Add the highest height in the view of the current row when the line is wrapped, and record it
  • Step 5: The width of the final ViewGroup is the maximum width of each row of the View recorded, and the height is the cumulative height
  • Step 6: Record each View in action units
  • Step 7: Remember to deal with the last line, because it is judged to be a newline record, many cases do not meet the newline requirements. At this point the onMeasure() method code is complete
  • Step 8: Loop through onLayout() to get the View for each row, then loop through the width and height of the View

Margin cannot be obtained in ViewGroup

Java solution:

Override these three methods:

/ * * * start * / @ child controls access to marge method Override protected LayoutParams generateDefaultLayoutParams () {return new MarginLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); } @Override protected LayoutParams generateLayoutParams(LayoutParams p) { return new MarginLayoutParams(p); } @Override public LayoutParams generateLayoutParams(AttributeSet attrs) { return new MarginLayoutParams(getContext(), attrs); } // the child control gets the marge method stopCopy the code

Direct strong transfer types do not match

MarginLayoutParams layoutParams = (MarginLayoutParams) childAtView.getLayoutParams(); Layoutparams. leftMargin // leftMargin layoutparams. rightMargin // rightMargin layoutparams. topMargin // test margin LayoutParams. BottomMargin / / margin under testCopy the code

Kotlin solution:

override fun generateLayoutParams(p: LayoutParams?) : LayoutParams? { return MarginLayoutParams(p) } override fun generateLayoutParams(attrs: AttributeSet?) : LayoutParams? { return MarginLayoutParams(context, attrs) } override fun generateDefaultLayoutParams(): LayoutParams? { return MarginLayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT) }Copy the code
val layoutParams = childView.layoutParams as MarginLayoutParams
Copy the code

Effect:



\

Kotlin complete code

Java complete code

Complete the project

Blogger page

Original is not easy, your praise is my biggest support ~