Add a margin to LinearLayout in Android

笑着哭i 提交于 2019-12-23 12:33:49

问题


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


回答1:


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 FrameLayouts 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;


来源:https://stackoverflow.com/questions/8154716/add-a-margin-to-linearlayout-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!