Increase layout loading speed 200%
Generally, when writing a page, everyone writes the layout through xml, and loads the xml layout into memory through set contentView or LayoutInflater.from(context).inflate method.
Our team has also explored many solutions on this issue. Once it reached the other extreme, completely abandoning xml, all controls are new through java, even directly in the canvas, so although the performance is indeed improved, but the code is gone. A little bit of readability and maintainability. We later reflected on the code to see the machine, or to show it? ? Maybe X2C has given us an answer.
In order to preserve the advantages of xml and solve the performance problems it brings, we developed the X2C solution. That is, during the compilation and generation of the APK, the translation of the layout that needs to be translated generates the corresponding java file, so that the developer writes the layout or writes the original xml, but for the program, the runtime loads the corresponding java file. We use APT (Annotation Processor Tool) + JavaPoet technology to complete the operation of the whole process during the compilation [Annotation] -> [Resolve] -> [Translate xml] -> [Generate java].
After the development integration, we did a simple test, the performance comparison is as follows
| Loading method | frequency | Average load time |
|---|---|---|
| XML | 100 | 30 |
| X2C | 100 | 11 |
Add dependencies in the build.gradle file of the module
annotationProcessor 'com.zhangyue.we:x2c-apt:1.1.2'
implementation 'com.zhangyue.we:x2c-lib:1.0.6'Add annotations to any java class or method that uses the layout.
@Xml(layouts = "activity_main")Create an X2C_CONFIG.xml file under the module, which defines the mapping between attributes and methods. If the receiver is a view, write the view. Otherwise fill in params.
<x2c-config>
<attr name="app:mixColor" toFunc="view.setMixColor(int)" />
<attr name="android:layout_marginTop" toFunc="params.topMargin=int" />
</x2c-config>Replace where you originally used set content view or inflate, as follows:
this.setContentView(R.layout.activity_main); --> X2C.setContentView(this, R.layout.activity_main);LayoutInflater.from(this).inflate(R.layout.activity_main,null); --> X2C.inflate(this,R.layout.activity_main,null);………| Attribute name | Attribute name |
|---|---|
| android:textSize | app:layout_constraintRight_toLeftOf |
| android:textColor | app:layout_constraintBottom_toTopOf |
| android:text | app:layout_constraintTop_toTopOf |
| android:background | app:layout_constrainedHeight |
| view all |
QQ群:
870956525,Add please specify fromX2CWelcome everyone to use, the project will continue to maintain
Another: welcome to joinIReader family, study new Android technologies together. Please send your resume
[email protected],Indicate the direction of employment。
…No open issues yet, or sync has not completed.