In many cases, the layout in xml cannot meet our needs. At this time, we need to use code for Dynamic Layout. Some problems were encountered during the dynamic layout of RelativeLayout the previous day. Now we have solved the problem and shared it.
I now create four views dynamically in RelativeLayout, which is the effect of two rows and two columns.
1. Add the first View.
RelativeLayout layout = (RelativeLayout) findViewById (R. layout. rl );
ImageView item1 = new ImageView (this );
Item1.setImageResource (R. drawable. x); // set the image
RelativeLayout. LayoutParams lp = new RelativeLayout. LayoutParams (
LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT );
Lp. addRule (RelativeLayout. ALIGN_PARENT_LEFT); // align with the left side of the parent container
Lp. addRule (RelativeLayout. ALIGN_PARENT_TOP); // align with the upper side of the parent container
Lp. leftMargin = 30;
Lp. topMargin = 30;
Item1.setId (1); // set the View id
Item1.setLayoutParams (lp); // you can specify layout parameters.
Layout. addView (item1); // Add a subview to RelativeLayout
2. Add the second View.
ImageView item2 = new ImageView (this );
Item2.setImageResource (R. drawable. x); // set the image
RelativeLayout. LayoutParams lp = new RelativeLayout. LayoutParams (
LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT );
Lp. addRule (RelativeLayout. ALIGN_PARENT_RIGHT );
Lp. addRule (RelativeLayout. ALIGN_PARENT_TOP );
Lp. rightMargin = 30;
Lp. topMargin = 30;
Item2.setId (2 );
Item2.setLayoutParams (lp );
Layout. addView (item2 );
3. Add the third View.
View childView1 = skinsLayout. getChildAt (0); First child View added to RelativeLayout
View item3 = createSkinItem (friendContext );
RelativeLayout. LayoutParams lp = new RelativeLayout. LayoutParams (
LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT );
Lp. addRule (RelativeLayout. ALIGN_PARENT_LEFT );
Lp. addRule (RelativeLayout. BELOW, childView1.getId (); // you can specify item3 under // chreceivview1.
Lp. leftMargin = 30;
Lp. topMargin = 30;
Item3.setId (3 );
Item3.setLayoutParams (lp );
Layout. addView (item3 );
3. Add the fourth View.
View childView2 = skinsLayout. getChildAt (1); // obtain the second sub-view of the container
ImageView item4 = new ImageView (this );
RelativeLayout. LayoutParams lp = new RelativeLayout. LayoutParams (
LayoutParams. WRAP_CONTENT, LayoutParams. WRAP_CONTENT );
Lp. addRule (RelativeLayout. ALIGN_PARENT_RIGHT );
Lp. addRule (RelativeLayout. BELOW, childView2.getId ());
Lp. rightMargin = 30;
Lp. topMargin = 30;
Item. setId (4 );
Item. setLayoutParams (lp );
Layout. addView (item );
This article is from "Li xiaoice" blog, please be sure to keep this source http://lovesong.blog.51cto.com/3976862/1183335