当前位置:网站首页>Customize the layout of view Foundation
Customize the layout of view Foundation
2022-06-11 05:18:00 【jxq1994】
When the previous section is completed measure After the operation , Next layout The process is actually relatively simple , The purpose is that the parent view follows
The size and layout parameters of the subview , Place the subview in the appropriate position . The core of layout parameters is to deal with gravity Parameters .
layout Process design ideas
Initial call layout() Function is from ViewRoot Class performTraversals(),host It's a View object ,View Class layout() The type of function is final, Its subclasses cannot overload the function , In order to make sure View In the system layout The process remains the same .
stay layout() Function , First call setFrame() Function to set the position specified in the parameter for the current view , And then back onLayou() function .ViewGroup Class is overloaded onLayout() function , And set its function type to a abstract type , therefore , be-all ViewGroup Instance must implement onLayout().View The system expects programmers to be able to onLayout() Function to modify the child views contained in the view layout operation , When the view is ViewGroup when , Programmers usually work in onLayout() Call child view in function chart child Of layout() Method , So as to complete the position allocation of the sub view . Of course , If the subview is also a ViewGroup example , The corresponding onLayout() function .
View class in layout() The prototype of the function is :
public void layout(int l, int t, int r, int b)
Parameter specifies the left position of the child view in the parent view 、 On 、 Right 、 The next position . Of this function
The internal process is as follows .
- call
setFrame(l, t, r, b)Save the position parameters .
These parameters will be saved to View Internal variables (mLeft、mTop、 mRight、mBottom), Before saving variables , We will first compare whether these parameters are the same as the original , If the same , Then do nothing , If it is different, it will be reassigned , And before the assignment , Will give
mPrivateFlagsAdd DRAWN identification , At the same time callinvalidatetell View The original position occupied by the system needs to be redrawn . Note that first callinvalidate(), Then assigned , Because what needs to be redrawn is the old area .
- Callback onLayout().
View As defined in
onLayout()Function does nothing by default ,View The system providesonLayout()The function is used to enable the parent view containing child views to be displayed in the systemonLayout()Function to allocate the position of the child view , Because of that , If it is the parent view , It has to be overloadedonLayout(), That's why ,ViewGroupClass caibaonLayout()The overload is modified to a abstract type .
- eliminate
mPrivateFlagsMedium LAYOUT_REQUIRED identification , because layout Your operation has been completed .
LinearLayout in onLayout() Internal process
LinearLayout There are two ways to arrange the subviews in , One is horizontal , The other is vertical , This section only describes the vertical mode
Workflow under .onLayout() Letter Count in The first First root According to the mOrientation change The amount sentence break yes water flat also yes Hang straight , Such as fruit yes Hang straight , Call layoutVertical() To begin layout operation .
1. Get the available width of the subview .
Here is the vertical layout , Why use the available width , Not the available height ?
because , Even in the vertical direction , The subview itself is also centered horizontally , To center, you need to know what width is available , So as to calculate the position of the left edge of the sub view , Such as chart Shown , The altitude information will be obtained in the following steps .
2. According to... In the parent view gravity attribute , Determine the starting position of the subview .
By default ,gravity yes TOP, application The program can be set to BOTTOM or person CENTER_VERTICAL, The corresponding starting positions of the three are shown in the figure .
3. The vertical position of the subview has been determined , And so it began for() Loop through assigning locations to each child view .
(1) Take out the... Of the subview
LayoutParams, And get the gravity Value . Pay attention to this gravity Values are not in subviewsandroid:gravityValue , It isandroid:layou_gravityValue , See the next section for an explanation of this .
( 2 ) root According to the gravity The value of determines the starting position in the horizontal direction , Divided into three , branch other yes LEFT、 CENTER HORIZONTAL And RIGHT, The corresponding starting positions of the three are shown in the figure .

( 3 ) transfer use
setChildFrame(), This function is actually called internallychild.layout()Set the layout location for the subview .
thus ,LinearLayout This completes the process of assigning layout positions to the included sub views .
TextView in gravity And layout The relationship between
As mentioned in the previous section , In the subview gravity The value of is not android:gravity Value , and yes android:layout__gravity, This is a
What's going on ?
This question actually contains an important concept , That's it LayoutParams How is it assigned . Applications can be found in layout.xml Use in documents such as < LinearLayout >、< TextView > The tag defines an interface . Whether it's ViewGroup still View, These tags define just one view , And cannot define LayoutParams, because LayoutParams As its name says , It is a layout attribute , When a view is not laid out, where does the layout attribute come from ?
and stay too Go to Of open Hair the Examination in , Big home A few Almost all send use too android:layout_height、android:layout_width、 android:gravity etc. XM L The syntax is a LinearLayout or person TextView Add the corresponding layout properties , And these values seem to work properly , On the surface , It is the corresponding view LayoutParams value , How does this explain ?
in addition , stay LayoutInflater There is one in the class inflate(int resId,View root) function , in the majority of cases , You call this
Function time , The second parameter root All is empty . What is the meaning of this parameter ? Why should it be empty in most cases ?
To answer the above questions , It is necessary to figure out how the internal system is from a XM L Create a corresponding file View Tree object ,
In the following paragraph XML Code as an example to illustrate the process :
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="200dp"
android:layout_height="60dp"
android:background="@color/white"
android:text="am i center_vertical"
android:gravity="center_horizontal"/>
<ListView
android:layout_width="300dp"
android:layout_height="100dp"
android:background="@color/black"/>
</LinearLayout>
This code contains a LinearLayout, It also contains two sub views , It's a TextView And one ListView.
from XML The corresponding... Is constructed in the file View The tree is in
Layoutlnflaterin Ofinflate()Function , If this code is used assetContentView()Parameters of , Will be treated as Activity The interface of , thatLinearLayoutAs defined inlayout_widthAnd height It all makes sense . But if this code is just an application call inflate() Function to create a View object , that Welllayout_widthAnd height There's no point .
inflate()The function will first determine the parameters root Is it empty , If it is empty , So XML The root view in the file constructs a temporary
Of View object , Here isLinearLayoutobject , At this point theLinearLayoutDeclarativelayout_widthAnd height Is of no use . Next, continue to read XML In file TextView, Read TextView after , It is necessary to TextView Add toLinearLayoutin . Because to add , So there has to be aLayoutParamsobject , therefore ,inflate()In the function TextView As defined inlayout_widthAnd height Is the parameter , return transfer TextView Parent viewgenerateLayoutParams()function .
TextView The parent view of is LinearLayout, And in the LinearLayout OfgenerateLayoutParams(attrs)Function , Parameters attrs It is from TextView All attribute values declared in , except layout_width and height Xibu , Also contains background、text And all declared attribute values , butgenerateLayoutParams(atts)But I am only interested in four of them :
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
TypedArray a =
c.obtainStyledAttributes(attrs, com.android.internal.R.styleable.LinearLayout_Layout);
weight = a.getFloat(com.android.internal.R.styleable.LinearLayout_Layout_layout_weight, 0);
gravity = a.getInt(com.android.internal.R.styleable.LinearLayout_Layout_layout_gravity, -1);
a.recycle();
}
In the above code ,super(c,attrs) Will read layout_height and layout_width Properties of , As shown in the following code . Then continue to read weight Properties and gravity attribute , The names of these two attributes are layout_weight and layout_ gravity.generateLayoutParams(atts) Finally, according to TextView The above four attributes in the construct a LinearLayout.ayoutParams object , And with this object TextView Add to LinearLayout in .
Let's look back at the questions raised above ,< TextView > Included in the label
android:layout_width、height Etc. is not defined LayoutParams object , It just provides the structure LayoutParams The value required for the parameter , And the real structure LayoutParams Object is its parent view , What will these parameters ultimately produce LayoutParams It depends on TextView In the parent view ofgenerateLayoutParams(attrs)The concrete realization of .
That's why we used... In the previous section
layout_gravityinstead of gravity Why , Because in LinearLayout
OfgenerateLayoutParams()Function , It's aandroid:layout_gravityThe attribute value is assigned toLayoutParams.gravity, instead ofandroid:gravity. in fact ,android:gravityProperties will be used as TextView Internal parameters ,TextView Inside onDraw() The function will be based onandroid:gravityThe value of determines where the text is displayed .
And when you call
setContentView(int resld)when , The system also callsinflate()Method from the specified XML In the document View Trees , And call time parameters root The setting is an internal one FrameLayout object .root The meaning of the parameter is that it will raise for generateLayoutParams() function , This function produces LayoutParams Object will be used as XML The views contained in the file are added to root Layout properties when .
If you're in one XM L Only one... Is defined in the file TextView label , And then call inflate(xml, null) From this XML
In file infalte a TextView object , Then the TextView Included in the tag android:layout_width、height It won't make any sense . When you Want to hold infalte Out Come on Of TextView Object is added to a ViewGroup when , You must also construct a LayoutParams object .
边栏推荐
- 点击图标不灵敏咋整?
- Go unit test example; Document reading and writing; serialize
- Huawei equipment is configured with bgp/mpls IP virtual private network address space overlap
- 项目-智慧城市
- How much current can PCB wiring carry
- 35.搜索插入位置
- Restoration of binary tree -- number restoration
- Conversion relationship between coordinate systems (ECEF, LLA, ENU)
- go MPG
- Opencv learning path (2-3) -- Deep parsing imshow function
猜你喜欢

Zed2 camera manual

在未来,机器人或 AI 还有多久才能具备人类的创造力?

KD-Tree and LSH

华为设备配置通过GRE隧道接入虚拟专用网

KD-Tree and LSH

PCB走線到底能承載多大電流

Thesis 𞓜 jointly pre training transformers on unpaired images and text

C (I) C basic grammar all in one
![[NIPS2021]MLP-Mixer: An all-MLP Architecture for Vision](/img/89/66c30ea8d7969fef76785da1627ce5.jpg)
[NIPS2021]MLP-Mixer: An all-MLP Architecture for Vision

New product pre-sale: 25g optical network card based on Intel 800 series is coming
随机推荐
华为设备配置通过GRE接入虚拟专用网
Preliminary test of running vins-fusion with zed2 binocular camera
Reverse thinking: making cartoon photos real
Target detection - personal understanding of RCNN series
code
Poverty has nothing to do with suffering
MySQL nested sorting: first sort and filter the latest data, and then customize the sorting of this list
What is the difference between gigabit network card and 10 Gigabit network card?
Vins fusion GPS fusion part
Top 100 video information of station B
BP neural network derivation + Example
一大厂95后程序员对部门领导不满,删库跑路被判刑
Lr-link Lianrui fully understands the server network card
Deep extension technology: intelligent OCR recognition technology based on deep learning has great potential
Following the wave of lack of core, Lianrui launched a number of gigabit network card solutions
Titanic rescued - re exploration of data mining (ideas + source code + results)
华为设备配置BGP/MPLS IP 虚拟专用网地址空间重叠
Combien de courant le câblage des PCB peut - il supporter?
Section I: classification and classification of urban roads
KD-Tree and LSH