我是android开发的新手,我想为我的视图增加边距,但是我无法使其正常工作。
这是我的代码:
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);
为什么这不起作用?谢谢!
答案 0 :(得分:1)
您应该这样做:
LayoutParams param = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
param.setMargins(left, top, right, bottom);
view.setLayoutParams(param);
答案 1 :(得分:0)
创建图标后,首先应为其生成一个ID:
icon.setId(View.generateViewId());
然后,删除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);
我还没有测试过,但这应该是朝着正确方向迈出的一步。
让我知道怎么回事。