Java – add margins for LinearLayout in Android

I have some problems setting the deposit!

body_content = (LinearLayout) findViewById(R.id.body_content);

int gSLength = 2;
 body_content.setPadding(10,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);
   ll1.setLayoutParams(params1);
   ll1.setBackgroundDrawable(getResources().getDrawable(R.drawable.line_down));
   fl.addView(ll1);

   body_content.addView(fl);
}

It doesn't work params1 setMargins(0,0);

Solution

First of all, Sherif's comment is correct: params1 should be FrameLayout An instance of layoutparams instead of LinearLayout LayoutParams.

The second thing is that framelayouts relies heavily on the gravity attribute When creating a new instance of a layout parameter for a FrameLayout child, gravity is set to - 1 by default (this is an invalid value for gravity) If the child's gravity is set to - 1, the entire margin is calculated to be skipped when calculating the layout This means that any set margin is ignored

So how to solve this problem? Very simple, set the correct value for gravity when setting the margin:

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

This should work However, the layout size you selected indicates that you want to position 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 setting the margin

LinearLayout.LayoutParams params1 = 
                    new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,30);
params1.gravity = Gravity.BOTTOM;
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>