Preface: The code layout is really pitted! But Google also offers several methods! Let's go through the code to layout!
Regardless of whether you create a relative layout or a linear layout. . It is inseparable from the LayoutParams
class. The role of the LayoutParams class is to set the properties of the layout. . Such as the width and height of the layout!
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
After setting the width and height of the layout, we load the width and height of the layout through: layout.setLayoutParams(params); method
We create a child control after we have created the layout. .
For example: create a textview;
TextView textView = new TextView(context);
After we have the TextView object, we need to set the height, width and other properties of the control;
设置宽高: LayoutParams t_Params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
After setting the width and height, it cannot meet the layout requirements of the practice. . For example: if you want this control to be on the right, how much distance from the top is required. but we all know
The layout is generally laid out from the left. . so:
t_Params .addRule(); This method provides where the control is located
在右:t_Params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
On the left: then there is no need to set
Since Google provides the addRule() method let's set the position of the control. . It will also provide a method of how far away
setMargins(int left, int top, int right, int bottom)
This method is very similar to android:layout_margin="". .
Suppose I setMargins(10, 20,0, 0);
At this time, the control becomes 10dp from the left and 20dp from the top;
After the basic properties of the control are set. . we pass
layout.addView(textView, t_Params);
layout is your layout object
textView is the control
Full code:
private Context context = MainActivity.this;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout = new RelativeLayout(MainActivity.this);
LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
layout.setLayoutParams(params);
TextView textView = new TextView(MainActivity.this);
LayoutParams t_Params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
t_Params.setMargins(20, 30, 40, 0);
t_Params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
textView.setText("23333333333333");
layout.addView(textView, t_Params);
setContentView(layout);
}