当前位置:网站首页>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
边栏推荐
- The vision group of Hegong University Sky team trained Day1 - machine learning, and learned to use the Yolo model
- Intelligent robots and intelligent systems (Professor Zheng Zheng of Dalian University of Technology) -- 2. Mobile Robot Perception
- 我在微软的这六个月
- 2022-07-23: given n items, each item has weight (w[i]) and value (v[i]), only two items can be selected at most, and the weight does not exceed bag. What is the maximum return value? N <= 10^5, w[i] <
- RBM contrast divergence
- Collection of binary tree topics
- UVA572油田 Oil Deposits题解
- Jetson AgX Orin source change
- Natural language processing hanlp
- Image feature Harris corner detection
猜你喜欢

RBM contrast divergence

SVM linear separable linear support vector machine

Debug No1 summarizes common solutions to bugs

*Project recurrence * project implementation of thesis based on contextbasedemotionrecognitionusingematicdataset

Hcip 13th day notes

MS SQL Server 2019 学习

Opencv project practice - credit card recognition

Anaconda cannot shut down the method of forced shutdown

Error when using PIP: pip is configured with locations that requires tls/ssl

hcip第八天笔记
随机推荐
NFT概念究竟是怎么回事。。全面了解NFT市场、技术和案例
生成模型与判别模型
2021-06-03pip error valueerror: unable to find resource t64.exe in package pip_ vendor.distlib
Tools for data visualization
Selenium basic knowledge automatically login Baidu Post Bar
Selenium basics controls the scroll bar of the browser
[target detection] IOU (intersection and combination ratio)
HCIP第七天
Implement a queue with two stacks.
JMeter stress test index interpretation
Kubernetes: (I) basic concepts
Selenium basic knowledge multi window processing
Zhouzhihua machine learning watermelon book chapter 2 model evaluation and selection - accuracy and model generalization evaluation method, self-help method and integrated learning
避坑,职场远离PUA,PUA常见的套路与话术你得了解一下!
Kubernetes:(一)基本概念
SVM linear separable linear support vector machine
Facing Tencent (actual combat) - Test Development - detailed explanation of interns (face experience)
*Code understanding * common function parsing in pytoch
Function analysis of e-commerce website development and construction
Digital twin demonstration project -- Talking about simple pendulum (2) vision exploration and application scenarios