Add margin to LinearLayout in Android

I have some problems setting up the field!

body_content = (LinearLayout) findViewById(R.id.body_content); int gSLength = 2; body_content.setPadding(10, 0, 10, 0); for (int i = 0; i < 1; i++){ FrameLayout fl = new FrameLayout(this); LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, 90); fl.setLayoutParams(params); LinearLayout ll1 = new LinearLayout(this); LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 30); params1.setMargins(0, 60, 0, 0); ll1.setLayoutParams(params1); ll1.setBackgroundDrawable(getResources().getDrawable(R.drawable.line_down)); fl.addView(ll1); body_content.addView(fl); } 

params1.setMargins (0, 60, 0, 0); does not work params1.setMargins (0, 60, 0, 0);

+4
source share
1 answer

First of all, the Sheriff’s comment is correct: params1 should be an instance of FrameLayout.LayoutParams , not LinearLayout.LayoutParams .
The reason is simple: ll1 is a child of FrameLayout, so it must accept layout options for FrameLayout children.

Secondly, FrameLayout highly dependent on the gravity attribute. When creating a new instance of the layout parameters for the FrameLayout child, gravity set to -1 by default (this is an invalid value for gravity). And if the value of gravity in a child is -1, when calculating the layout when calculating the entire field, it is skipped . This means that any value of the given field value is ignored.

So how to fix this? Simply set the correct gravity value when setting the field:

 LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 30); params1.gravity = Gravity.TOP; params1.setMargins(0, 60, 0, 0); 

That should work. But your choice of layout sizes suggests that you want to place the child LinearLayout at the bottom of the FrameLayout. This can be done by setting gravity to the bottom, in which case you can skip the field setting.

 LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 30); params1.gravity = Gravity.BOTTOM; 
+1
source

Source: https://habr.com/ru/post/1381520/


All Articles