Summary of using custom ViewGroup in Android

classification

Custom layout can be divided into two cases.

technological process

The process of customizing the view is: onmeasure() - > onlayout() - > ondraw(). When customizing the ViewGroup, don't implement OnDraw. Of course, there may be special requirements, such as coordinatorlayout.

Therefore, onmeasure and onlayout can basically do most of the viewgroups we contact. However, it is not enough to only know the size of the ViewGroup measured in onmeasure and the position of the child view calculated in onlayout.

For example, how can I set properties for child view of ViewGroup?

An example.

Write a custom ViewGroup and add an attribute to control the proportion of the size (length and width) of the child view in the ViewGroup.

If it is a LinearLayout, define a customlinearlayout first.

Other things aside, we need to add attributes to control the size of child view. Then first define that attribute in value / attr.xml (use customlinearlayout_layout to distinguish it from customlinearlayout. Of course, the name is optional).

This method will eventually be called when ViewGroup calls addview().

This params represents the configuration of the view. Viewgroup.layoutparams contains width and height. Linearlayout.layoutparams adds weight attribute and so on. Then we should implement a layoutparams. So that's it now.

Now we can use our attributes in XML.

However, it is not soft and has no effect.

So how to control the size of child view? Controlled by onmeasure, of course. Addview executes the following code.

In this way, onmeasure(), onlayout() will be repeated. After implementing the onmeasure () method, I will directly handle the size of the child view. Because I inherit the LinearLayout, I will actually handle the measurechildbeforelayout (). Finally, the size of the child view is processed during measurechildbeforelayout.

In this way, the initial requirements can be realized.

In fact, there are some details to deal with. The following code is.

To sum up

For Android development, there are many places where you need to customize your view, but most of them will have corresponding open source libraries. However, we should know how to customize a ViewGroup skillfully.

I am a forgetful person, so write in detail.

The complete code is stamped here.

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support 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
分享
二维码
< <上一篇
下一篇>>