当前位置:网站首页>Kotlin higher order function & DSL layout persuasion Guide
Kotlin higher order function & DSL layout persuasion Guide
2022-07-24 07:59:00 【Cupster】
Catalog
- One 、 background
- Two 、 Related introduction
- 3、 ... and 、 Practical application
- Four 、 summary
One 、 background :
Runtime app Open a page , The things that must be done are :
1. The first xml File loaded into memory
2. analysis xml label , Read layout
3. Render all levels View To screen
And if you use code to dynamically draw the page layout directly , You don't need this 1、2 Two time-consuming steps .
Actual test comparison , A simple single-layer layout page is 20ms->2ms A huge improvement around . If it is a complex or deeper page , Improve more .
There are advantages and disadvantages , Insufficient :
1. Code dynamic layout , Poor code readability
2. Page layout has changed , Maintenance is difficult
3. A lot of code , In the same category , The number of lines of code is easy to break 750 That's ok
4. The interface cannot be previewed , In order to improve the operation efficiency , At the expense of development efficiency
Two 、 Related introduction
2.1 Higher order function
Higher order function is a special function : Its parameter or return value is another function . For example, the parameter transfer callback used in normal development , You can omit the callback interface 、 Coding of implementation :
private fun exampleFun(emit: (bean: ImEventBean) -> Unit) {
...
...
val result = GsonUtils.fromJson(json, ImEventBean::class.java)
emit(result)
}exampleFun {
EventBusUtils.post(it)
}Or as : frequently-used let function
public inline fun <T, R> T.let(block: (T) -> R): R {
contract {
callsInPlace(block, InvocationKind.EXACTLY_ONCE)
}
return block(this)
}2.2、 Inline function
Simple understanding , Is compile time , Copy and paste the function body into the function call , Reduce the development of method stack once ( Local variable table 、 Operation stack and other incidental expenses )
Mainly use the scene , Used in conjunction with higher-order functions /Lambda Use . with Lambda With , Mainly to allow local return , Such as :
[email protected]
2.3 Kotlin Medium Lambda
Kotlin Medium Lambda function , Non private members who can access the recipient . Such as :
info.apply{
updateName(info.nickName)// Get non private members
info.age = mInput.text.toString()// Set non private members
}2.4 DSL Improve the readability of dynamic code layout
DSL(domain specific language), Full name “ Domain specific languages ”,DSL Focus on specific areas of operation / expression , With structural . for example HTML、SQL It is also a kind of structural DSL Language
be based on Kotlin With the recipient lambda(& Higher order function ) Characteristics of , combination DSL Readable structural properties , It can optimize the readability of dynamic layout code , Examples of practice are as follows :
ConstraintLayout {
layout_width = match_parent
layout_height = match_parent
ImageView {
layout_id = "ivBack"
layout_width = 28
layout_height = 28
margin_start = 16
margin_top = 18
src = R.drawable.ic_back
start_toStartOf = parent_id
top_toTopOf = parent_id
onClick = { onBackClick() }
}
TextView {
layout_width = wrap_content
layout_height = wrap_content
text = "commit"
textSize = 16f
textStyle = bold
align_vertical_to = "ivBack"
center_horizontal = true
}
}3、 ... and 、 Practical application
Here is only an example , To be specific demo&lib_dsl Subject to ,DemoGit
3.1 Higher order function extension View The construction of
inline fun ViewGroup.TextView(
style: Int? = null,
autoAdd: Boolean = true,
init: AppCompatTextView.() -> Unit
): TextView {
val textView =
if (style != null) AppCompatTextView(ContextThemeWrapper(context, style))
else AppCompatTextView(context)
return textView.apply(init).also { if (autoAdd) addView(it) }
}Then you can use it like this

3.2 Expand xml attribute
inline var View.layout_width: Number
get() {
return 0
}
set(value) {
val w = if (value.dp > 0) value.dp else value.toInt()
val h = layoutParams?.height ?: 0
updateLayoutParams<ViewGroup.LayoutParams> {
width = w
height = h
}
}3.3 Define top-level attribute values
val wrap_content = ViewGroup.LayoutParams.WRAP_CONTENT val match_parent = ViewGroup.LayoutParams.MATCH_PARENT
And then you can do it in kt This is used in the code

3.4 Get controls
because DSL Structured construction layout , We can declare member variables directly , structure view It is directly assigned to , Or when you need it later , Then through the father view.findViewById() obtain
lateinit var btnMenu: View
...
mRootView = context.ConstraintLayout {
...
// Direct assignment
btnMenu = TextView {
// Statement id Subsequent to findViewById()
layout_id = "tvMenu"
layout_width = wrap_content
layout_height = wrap_content
textSize = 16F
text = " menu "
}
...
}
3.5 Use
Separate the dynamic layout code into a class , And use in it DSL Write layout . Then initialize where necessary 、 Use
/** Layout dsl Equivalent to viewBinding file */
private val contentViewDsl by lazy { SecondActivityDslLayout().inflate(this) } val beforeMills = System.currentTimeMillis()
// Lazy loading ,setView
setContentView(contentViewDsl.getRoot())
val totalMills = System.currentTimeMillis() - beforeMills
Log.d(this.javaClass.simpleName, "================= Page construction takes time :${totalMills}ms")
// similar ViewBinding Use controls
contentViewDsl.tvTitle.text = " Time consuming :${totalMills}ms"3.6 Effect and analysis
Final operation effect and xml Agreement , You can run the code to see .
And xml Compared with the first rendering layout dsl It takes longer .
We go through Android Studio Tools , see DSL Layout .kt file After compilation , The discovery is only Demo Simple pages , The compiled Java The code is already thousands of lines . Part of the reason is that the extension function uses inline keyword , Another part of the reason is kotlin Its own characteristics .
above Demo Yes, not involved Click or change monitoring Pure UI Layout code , If it is a normal business page , So the generated Java Class files will be very large , In the later stage, it still needs to be optimized .


Four 、 summary
1. Use DSL Code dynamic layout , It solves the problem of poor readability of ordinary code , Readability and xml flat
2. Page layout has changed , Less difficult to maintain , Easy to expand
3. Write less code , Interface rendering efficiency is much better than xml
4. The interface cannot be previewed because it is hard , In order to improve the operation efficiency , At the expense of development efficiency , It is suggested that users of lower versions should not be considered in the later stage , Switch to Jetpack Compose
5. In the early DSL Writing the extension library takes a lot of time , It is difficult to promote in practice
6.DSL Layout .kt Code to Java Code , The amount of code increases as the complexity of the page increases
To make a long story short , Wait for permission to give up 5.0 The following users , Go straight up Jetpack Compose Well .
5、 ... and 、 Code
边栏推荐
- *Yolo5 learning * data experiment based on yolo5 face combined with attention model se
- 55. Jumping game
- NFT是什么?一篇文章搞懂NFT的概念
- Tools for data visualization
- 13. Unity2d horizontal version of two-way platform that can move up, down, left and right (two-way walking + movable + independent judgment) + random platform generation
- Workspace creation
- *Yolo5 learning * data experiment based on yolo5 face combined with attention model CBAM
- Install librosa using Tsinghua image
- Common DOS commands
- 从零开始C语言精讲篇3:函数
猜你喜欢

Hcip day 8 notes

Facing Tencent (actual combat) - Test Development - detailed explanation of interns (face experience)

*Yolo5 learning * data experiment based on yolo5 face combined with attention model CBAM

EZDML逆向工程导入数据库分析实操教程

hcip第十三天笔记

What is NFT? An article to understand the concept of NFT

Qt|字符串生成二维码功能

Postman extracts the token parameter value in the response header and sets it as an environment variable, with code attached

rbm 对比散度

13.Unity2D 横版 可上下左右移动的双向平台(双向行走+可移动+单独判定)+随机平台生成
随机推荐
About how to set colored fonts on the terminal
*Code understanding * common function parsing in pytoch
RBM contrast divergence
Multiple optimization methods print prime numbers between 100 and 200
33 introduction to sparksql, dataframe and dataset
P1305新二叉树题解
Anaconda cannot shut down the method of forced shutdown
Hcip day 7
OpenGL camera and periodic review
Natural language processing hanlp
Vertex buffer and shader (the cherno + leranopongl) notes
避坑,职场远离PUA,PUA常见的套路与话术你得了解一下!
[target detection] IOU (intersection and combination ratio)
Basic operation of queue
Hegong sky team vision training Day2 - traditional vision, opencv basic operation
Math。 Round, numeric rounding, underlying code parsing
Why is knowledge base important? This is the best answer I've ever heard
Opencv project - credit card recognition (learning record)
The difference between session and cookie
hcip第八天笔记