Android: viewgroup.marginlayoutparams does not work properly

I use it to programmatically set margins, but it doesn't work. Margins are not applied. In the constructor:

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

resolvent:

According to your comments, you will set parameters when the view does not have layoutparams, and they will be overwritten when you attach the view to the layout. What I suggest you do is move the settings of layoutparams to the onattachedtowindow method. Then, you will be able to use getlayoutparams() to obtain layoutparams and modify them

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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>