Java code controls the layout_Margin Parameter
Problem description
I am working on the android interface today, but I need to use java code to dynamically generate an interface. It is not difficult to write it, But I encountered a problem when controlling the interval between each line and the uplink. In the layout xml file, you can control the distance between the current view and the next view by writing android: layout_marginLeft android: layout_marginTop. But how to write in java?
Solution
In java code, I only found setPadding (left, top, right, bottom), but there is no setMargin or setLayoutMargin method to control the view interval.
I found the Official Google website and found the ViewGroup. MarginLayoutParams class on the official website. The information is as follows:
XML Attributes
Attribute Name Related Method Description
Android: layout_marginBottom setMargins (int, int) Specifies extra space on the bottom side of this view.
Android: layout_marginEnd setMarginEnd (int) Specifies extra space on the end side of this view.
Android: layout_marginLeft setMargins (int, int) Specifies extra space on the left side of this view.
Android: layout_marginRight setMargins (int, int) Specifies extra space on the right side of this view.
Android: layout_marginStart setMarginStart (int) Specifies extra space on the start side of this view.
Android: layout_marginTop setMargins (int, int) Specifies extra space on the top side of this view.
We can see that their attributes still have corresponding methods: setMargins, setMarginEnd, and so on.
But how can this method be used. For this reason, I made a series of explorations and found that they should be used in the following ways:
LinearLayout line = (LinearLayout) findViewById(R.id.layoutbtnlinear_aboutme); LinearLayout.LayoutParams params = (LayoutParams) line.getLayoutParams(); params.setMargins(0, 1, 0, 0); line.setLayoutParams(params);
However, this method is still a bit problematic. My LinearLayout is generated in java code. Well, continue to find the method:
LinearLayout ll = new LinearLayout(this);ll.setOrientation(LinearLayout.VERTICAL);LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams( LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);layoutParams.setMargins(30, 20, 30, 0);Button okButton=new Button(this);okButton.setText(text);ll.addView(okButton, layoutParams);