Implementation method of Android custom ViewGroup

Several common implementations of ViewGroup are provided in Android, including LinearLayout, relativelayout, FrameLayout, etc. These viewgroups can meet our general development needs, but for complex interface requirements, these layouts are stretched. Therefore, customized viewgroups can be found everywhere in the applications we have contacted.

To implement a custom ViewGroup, the first step is to learn custom attributes, which will make us more flexible when configuring layout files. The custom attribute is to declare an attrs.xml file in the value directory.

Here we declare two custom attribute sets. The attributes in the cascadeview group are set for our custom cascadeview group component, that is, the attributes that can be used in the < cascadeview group > tag in the layout file. Another cascadeview group_ Layoutparams is the property set for the child view in the cascadeview group.

Before writing the code, we also set a default width and height for cascadelayout. These two attributes are defined in dimensions. XML.

Let's start writing the custom component cascadelayout.

The code is slightly longer, but the structure is still very clear.

1) Configure the value of the attribute in the constructor or in the XML file. Get the properties we set in the layout through the methods in typedarray, and save them in the member variable.

2) Construct a custom internal class layoutparams. By constructing this internal class, it is convenient for us to save their attribute values when measuring our sub views, so that we can layout in the layout stage.

3) Generatelayoutparams(), generatedefaultparams(), etc. Return our custom layoutparams in these methods. As to why you want to override these methods, you can see the addview () method of the ViewGroup class.

4) Measure phase. In the measure phase, we will measure our own size and the size of the quantum view, and save the information of the child view in layoutparams.

5) Layout phase. Layout their positions according to the information of each sub view.

Finally, add the layout file.

The results are as follows:

The above is the whole content of the. I hope I can give you a reference and support more programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>