Android:ViewGroup.MarginLayoutParams 不工作

Android: ViewGroup.MarginLayoutParams not working

我用它以编程方式设置边距,但它不起作用,边距未应用。在构造函数中:

public TimeWindow(Context context, int pixels, int left, int top){
    super(context);
    ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(pixels, pixels);
    params.setMargins(left, top, 0, 0);
    this.setLayoutParams(params);
}

将 MarginLayoutParams 替换为此 LayoutParams 为:

 LayoutParams params= new LinearLayout.LayoutParams( pixels, pixels);
params.setMargins(left, top, 0, 0);
this.setLayoutParams(params);

您必须将 LinearLayout.LayoutParams 替换为您正在处理的布局。希望有用

从您的评论中推断,当您的 View 还没有 LayoutParams 时,您正在设置参数,并且当您将 View 附加到布局时,它们将被覆盖.我建议您将 LayoutParams 的设置移至 onAttachedToWindow 方法。然后你就可以用getLayoutParams()获得LayoutParams并修改

private final int mPixelSize;
private final int mLeftMargin;
private final int mTopMargin;

public TimeWindow(Context context, int pixels, int left, int top){
    super(context);
    mPixelSize = pixels;
    mLeftMargin = left;
    mTopMargin = top;
}

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    if (getLayoutParams() instanceof MarginLayoutParams){ 
        //if getLayoutParams() returns null, the if condition will be false
        MarginLayoutParams layoutParams = (MarginLayoutParams) getLayoutParams();
        layoutParams.width = mPixelSize;
        layoutParams.height = mPixelSize;
        layoutParams.setMargins(mLeftMargin, mTopMargin, 0, 0);
        requestLayout();
    }
}