问题
I've been trying to set margins for a programmatically created LinearLayout
LinearLayout linearLayout = new LinearLayout(this);
setMargins(linearLayout,20,20,20,20);
private void setMargins (View view, int left, int top, int right, int bottom) {
if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
final float scale = getBaseContext().getResources().getDisplayMetrics().density;
// convert the DP into pixel
int l = (int)(left * scale + 0.5f);
int r = (int)(right * scale + 0.5f);
int t = (int)(top * scale + 0.5f);
int b = (int)(bottom * scale + 0.5f);
p.setMargins(l, t, r, b);
view.requestLayout();
}
}
But it didn't work so I tried this from another answer here
parameter = (LinearLayout.LayoutParams) linearLayout.getLayoutParams();
parameter.setMargins(leftMargin, parameter.topMargin, parameter.rightMargin, parameter.bottomMargin); // left, top, right, bottom
linearLayout.setLayoutParams(parameter);
But I get "Cannot solve symbol parameter"
How can I set margins to programmatically created view?
回答1:
Try this:
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(10, 10, 10, 10);
linearLayout.setLayoutParams(layoutParams);
来源:https://stackoverflow.com/questions/55207828/android-how-to-set-linearlayout-marging-programmatically