简体   繁体   English

如何以编程方式在视图上设置边距?

[英]How to set margin on view programmatically?

I am new to android development and I am trying to add margins to my view but I have not been able to get it to work. 我是android开发的新手,我想为我的视图增加边距,但是我无法使其正常工作。

Here's my code: 这是我的代码:

ConstraintLayout layout = new ConstraintLayout(this);

    final float scale = getResources().getDisplayMetrics().density;
    layout.setMinHeight((int)(100*scale));
    layout.setMaxHeight((int)(100*scale));

    CircleImageView icon = new CircleImageView(this);
    icon.setImageResource(image);
    icon.setBorderWidth(3);

    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams((int)(90*scale), (int)(90*scale));
    icon.setLayoutParams(layoutParams);

    ViewGroup.MarginLayoutParams marginParams = new ViewGroup.MarginLayoutParams(icon.getLayoutParams());
    marginParams.setMargins(100, 0, 0, 0);
    RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(marginParams);
    icon.setLayoutParams(params);

    layout.addView(icon);

Why isn't this working? 为什么这不起作用? Thanks! 谢谢!

You should do like this: 您应该这样做:

LayoutParams param = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
param.setMargins(left, top, right, bottom);
view.setLayoutParams(param);

After you have created the icon, you should first generate an id for it: 创建图标后,应首先为其生成一个ID:

icon.setId(View.generateViewId());

Then, remove the setMargins line and add these lines below layout.addView(icon): 然后,删除setMargins行并将这些行添加到layout.addView(icon)下:

ConstraintSet set = new ConstraintSet();
set.clone(layout);

set.constrainWidth(icon.getId(), (int)(90*scale));
set.constrainHeight(icon.getId(), (int)(90*scale));

set.connect(icon.getId(), ConstraintSet.TOP, ConstraintSet.PARENT_ID, ConstraintSet.TOP, 0);
set.connect(icon.getId(), ConstraintSet.START, ConstraintSet.PARENT_ID, ConstraintSet.START, 100);

set.applyTo(layout);

I haven't tested it but it should be a step in the right direction. 我尚未测试过,但这应该是朝正确方向迈出的一步。

Let me know how it goes. 让我知道事情的后续。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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