SoFunction
Updated on 2025-04-05

Android dynamic layout summary

Compared with static layout, dynamic layout does not need to transform XML into layout code, which improves a certain efficiency, and of course it can be ignored. Dynamic layout is mainly flexible, and you can quickly modify the layout in the code and directly use controls for business logic development. However, the code volume is usually relatively large, and maintenance is not as convenient as static layout. However, as an Android developer, mastering certain dynamic layout skills can sometimes improve certain code development efficiency at work.

In dynamic layout, if you want to implement a layout, you usually first create objects of five layouts. Then set the properties of these objects, and then add sub-layouts or controls to it.

Take RelativeLayout as an example.

 RelativeLayout mLayout = new RelativeLayout();
//Set the child control property object of RelativeLayout and set its dimension style.  Each GroupView has a LayoutPrams, which is used to set the child control to occur.

 params = new (LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
//Add child controlImageView iv = new ImageView(getActivity());
(.tab_icon_conversation_normal);
//Set the position properties of the child control in RealtiveLayout.(RelativeLayout.CENTER_IN_PARENT, ); //Add attributes to iv //Add iv to mLayoutmLayout .addView(iv, params); 

From the last sentence, we can see that the properties set by the params object reference are all used on the ImageView subcontrol, and then add the iv and params to RealtiveLayout together.

Summary of the dynamic layout method of Android

//Absolute layout

AbsoluteLayout abslayout=new AbsoluteLayout (this);
setContentView(abslayout);
Button btn1 = new Button(this);
(”this is a button”);
(1);
 lp1 =
new (
.WRAP_CONTENT,
.WRAP_CONTENT,
0,100);
(btn1, lp1);

//Relative layout

RelativeLayout relativeLayout = new RelativeLayout(this);
setContentView(relativeLayout);
AbsoluteLayout abslayout=new AbsoluteLayout (this);
 lp1 = new (.WRAP_CONTENT, .WRAP_CONTENT);
(RelativeLayout.ALIGN_PARENT_TOP);
(RelativeLayout.CENTER_HORIZONTAL, );
(abslayout ,lp1);

//Linear layout

LinearLayout ll = new LinearLayout(this);
EditText et = new EditText();
(et);
// Methods to dynamically add layout 1. LinearLayout ll = (LinearLayout)().inflate(.main1,null); setContentView(ll); LinearLayout ll2 = (LinearLayout)().inflate(.main2,ll); // In this way, main2 is added to the root node of main1 as a sub-layout of main1.//How to dynamically add layouts2 addView. LinearLayout ll = (LinearLayout)().inflate(.main1,null); setContentView(ll); LinearLayout ll2 = (LinearLayout)().inflate(.main2,null); (ll2);