保证金加入的LinearLayout Android中 [英] Add a margin to LinearLayout in Android

查看:150
本文介绍了保证金加入的LinearLayout 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);
}

它不工作 params1.setMargins(0,60,0,0);

推荐答案

首先,谢里夫的评论是正确的: params1 应该是一个实例 FrameLayout.LayoutParams ,而不是 LinearLayout.LayoutParams 。结果
原因很简单: LL1 是的FrameLayout的孩子,所以它采取的布局PARAMS一个孩子的FrameLayout

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.

第二件事是,的FrameLayout 取值很大程度上取决于重力属性。当一个孩子的FrameLayout创建布局PARAMS的新实例,<一个href=\"http://google.com/$c$csearch#uX1GffpyOZk/core/java/android/widget/FrameLayout.java&q=FrameLayout%20package%3aandroid&type=cs&l=451\"相对=nofollow> 重力默认情况下的设置为 1 (这是对于重力无效的值)的。如果孩子的重力设置为-1,整个保证金计算得到的跳过在计算布局。这意味着任何一组边距值被忽略。

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.

那么如何解决这个问题? pretty简单,设置保证金时设置重力正确的值:

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

这应该工作。但是,你的布局尺寸的选择,建议你要孩子的LinearLayout在的FrameLayout的底部位置。这可以通过设置重力底部来完成,你可以跳过在这种情况下设置的余量。

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;

这篇关于保证金加入的LinearLayout Android中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆