简体   繁体   中英

Add a margin to LinearLayout in Android

I have some problems with setting margin!

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);
}

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

First of all, Sherif's comment is correct: params1 should be an instance of FrameLayout.LayoutParams and not LinearLayout.LayoutParams .
The reason is simple: ll1 is a child of a FrameLayout, so it has to take the layout params for a FrameLayout children.

The second thing is that FrameLayout s depend heavily on the gravity attribute. When creating a new instance of the layout params for a FrameLayout child, gravity is set to -1 by default (which is an invalid value for a gravity) . And if the child's gravity is set to -1, the whole margin calculation gets skipped while calculating the layout. Which means any set margin value gets ignored.

So how to fix that? Pretty simple, set a correct value for the gravity when setting a margin:

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 dimensions suggests that you want to position the child LinearLayout at the bottom of the FrameLayout. That can be accomplished by setting the gravity to bottom, you can skip setting a margin in this case.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM