ArticleDirectory
UsageCodeTo create a view, you do not use XML to construct the view of the activity or every itemview in the listview (as shown below ),
Public Class Helloworld Extends Activity {
Private Textview mtextview;
@ Override
Public Void Oncreate (bundle savedinstancestate ){
Super . Oncreate (savedinstancestate );
Setcontentview (R. layout. Main );
Mtextview = (Textview) findviewbyid (R. Id. textview );
}
}
Instead, you can directly use code to create controls and the entire view (as shown below ),
Public Class Helloworld Extends Activity {
Private Textview mtextview;
@ Override
Public Void Oncreate (bundle savedinstancestate ){
Super . Oncreate (savedinstancestate );
Linearlayout Layout = New Linearlayout ( This );
Layout. setorientation (linearlayout. Vertical );
Layout. setlayoutparams ( New Layoutparams (layoutparams. fill_parent, layoutparams. fill_parent );
Mtextview = New Textview ( This );
Mtextview. settext ( " Hello World " );
Layout. addview (mtextview );
Setcontentview (layout );
}
}
Benefits:
1. High Efficiency.
Because the efficiency of the findviewbyid function is very low.
2. Applications can be reduced.ProgramThe size of the SDK (APK file.
3. After obfuscation, the layout cannot be easily cracked.
Postscript:
1. When the project is large, or there are too many interfaces, you will find a lot of repeated code. Therefore, when the project starts, you should consider
From activity to view creation, you must consider reusing or extracting abstract parts and encapsulating them.
2. if the UI is highly likely to change, the location is often adjusted, or the project starts, you need to consider writing in XML first, waiting for stability or after the project, because the performance needs to consider using code
To write the layout.