5

I used this to set the margin programmatically, but it does not work, the 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);
}
nomnom
  • 1,560
  • 5
  • 17
  • 31
  • Try getting the existing layout param of the view and set the margin for that. – Triode Dec 14 '15 at 11:37
  • @Triode thank you for the reply. I tried to get the params. But it seems that the params is null when I tried to get them. Maybe because this code is in the constructor of a custom view object. – nomnom Dec 14 '15 at 11:43
  • I'd imagine they could be null if the views haven't been laid out yet (if the above is in a view constructor). – akodiakson Dec 14 '15 at 11:46

2 Answers2

4

Deducing from your comments, you're setting your params when your View does not have LayoutParams yet, and they are being overwritten when you attach your View to the layout. What I would advice you to do is to move the setting of your LayoutParams to the onAttachedToWindow method. Then you will be able to obtain LayoutParams with getLayoutParams() 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();
    }
}
Bartek Lipinski
  • 30,698
  • 10
  • 94
  • 132
0

Replace MarginLayoutParams with this LayoutParams as :

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

you have to replace LinearLayout.LayoutParams with your layout on which you are working on. Hope it will work

Kapil Rajput
  • 11,429
  • 9
  • 50
  • 65