Android percentage layout details and example code

Android percentage layout

1. Import: compile 'com. Android. Support: percent: 24.0.0'

2. Click the open source code to see that there are mainly two layout classes, percentframelayout and percentrelativelayout, and a tool class, percentlayouthelper.

3. Click the layout class, such as the source code of percentrelativelayout, and you can see that the implementation is very simple.

Some methods of percentlayouthelper are called in onmeasure and onlayout. In addition, their own layoutparams are defined in onmeasure and onlayout, and this layoutparams is quite simple.

The key line of code here is in the onmeasure method, mhelper. Adjustchildren (widthmeasurespec, hightmeasurespec); Set the width and height of the child view by traversing the child view through the adjustchildren of the percentlayouthelper. The width and height are calculated by the value set in the layout file in the internal class of the percentlayouthelper.

4. Usage in layout: take percentrelativelayout as an example

Introduce the namespace of xmlns: app, and then app: layout_ Widthpercent = "50%" you can set the percentage of width and height. Quite simple.

5. However, there may be some other requirements during use, such as app: layout_ widthPercent="50%",app:layout_ Highpercentage = "50%" is relative to the width and height of the screen. If you want to display a square picture, take 50% of the width as the standard? At this time, it can be written as follows:

Using layout_ Aspectratio property, set app: Layout_ aspectRatio="100%",layout_ Aspect ratio is the aspect ratio. Don't set app: layout at this time_ The highpercentage property is. In the percentlayouthelper, the source code is as follows:

6. In addition, if we want to define our own percentlinearlayout, we can basically change the name and inherit from LinearLayout: public class percentlinearlayout extends LinearLayout. It's good to define our own layoutparams by imitating the layoutparams in percentrelativelayout.

But why doesn't the official provide a percentlinearlayout class directly, but only two percentframelayout and percentrelativelayout? Perhaps it is because LinearLayout itself has a weight attribute with a percentage effect.

Thank you for reading, hope to help you, thank you for your support to this site!

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
分享
二维码
< <上一篇
下一篇>>